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.*"/>

Or include folder

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

2.Writer each layer

Action(controller) layer:

package io.trashcode
public class HelloWorld{
public String hello() {
return "hello";
    private TCService service;
    public void add(){

Service layer:

package io.trashcode
public class TCService{
    private TCDAO tcDAO;
    public void 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();
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.