SpringMVC quick start @Controller @Service @Repository


Most of MVC model have three lays:

  • Controller layer

       - handle request

  • Service layer

       - implement your service logic 

  • Repository or DAO layer

       - operate data layer like DBMS,etc

So , in Spring MVC ,there are three types of annotation to mark such layer:

@Controller @Service @Repository

Actually , above annotation is one type of @Component

1.Firstly , register your component in Spring container

Set container scan folder:

<context:component-scan base-package="io.trashcode"/>

You can also set exclude folder

<context:component-scan base-package="io.trashcode">
    <context:exclude-filter type="regex" expression="com.thirdsource.*"/>
</context:component-scan>

Or include folder

<context:component-scan base-package="io.trashcode" user-default-filters="false">
    <context:include-filter type="regex" expression="io.trashcode.allcom.*"/>
</context:component-scan>

2.Writer each layer

Action(controller) layer:

package io.trashcode
public class HelloWorld{
@RequestMapping(value="/hello")
public String hello() {
return "hello";
}
    @Autowried
    private TCService service;
    public void add(){
        service.add();
    }
}

Service layer:

package io.trashcode
@Service(“tcService”)
public class TCService{
    @Resource
    private TCDAO tcDAO;
    public void add(){
        tcDAO.add();
    }
}

DAO layer:

Since we may have multiple data source , so we ‘d better to define a DAO interface , so that we can switch to different data source without change too many code.

public interface TCDAO {
    public void add();
}
@Repository("tcDAO")
public class TCDAOImpl implements TCDAO {
    public void add(){
    /*do some database staff , like connection ,prepared statment
*/
        System.out.println("hello Dao");
    }
}

Now ,we have a complete MVC components.