SpringMvc三层架构注解详解@Controller、@Service和@Repository

springvmc采用经典的三层分层控制结构,在持久层,业务层和控制层分别采用@Repository、@Service、@Controller对分层中的类进行注解,而@Component对那些比较中立的类进行注解

1. @Controller控制层

@Controller用于标记在一个类上,使用它标记的类就是一个SpringMvc Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。
@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器。
@Controller标记在一个类上还不能真正意义上说它就是SpringMvc的控制器,应为这个时候Spring还不认识它,这个时候需要把这个控制器交给Spring来管理。有两种方式可以管理:
<!--基于注解的装配-->
<!--方式一-->
<bean class="com.HelloWorld"/>
<!--方式二-->
<!--路径写到controller的上一层-->
<context:component-scan base-package="com"/>

Action层:

package com;
@Controller
public class HelloWorld{
	
	@RequestMapping(value="/showRegUser")
	public String printHello() {
		return "hello";
	}

    @Autowried
    private IocSerevce service;
    public void add(){
        service.add();
    }
}
component-scan默认扫描的注解类型是@Component,不过,在@Component的语义基础之上细化为@Reposity,@Service,@Controller.
有一个use-defaultbao'i-filters属性,属性默认是true,表示会扫描抱下所有的标有@Component的类,并注册为bean,也就是@Component的子注解@Service,@reposity等
如果只想扫描包下的@Controller或其他内容,则设置use-default-filters属性为false,表示不再按照scan指定的包进行扫描,而是按照指定包进行扫描
<context:component-scan base-package="com" user-default-filters="false">
    <context:include-filter type="regex" expression="com.tan.*"/>
</context:component-scan>

当没有设置use-default-filters属性或属性为true时,表示基于base-package包下指定扫描的具体路径。

2. @Service()


此注注解属于业务逻辑层,service或者manager层
默认按照名称进行装配,如果名称可以通过name属性指定,如果没有name属性,注解写在字段上时,默认去字段名进行查找,如果注解写在setter方法上,默认按照方法属性名称进行装配。当找不到匹配的bean时,才按照类型进行装配,如果name名称一旦指定就会按照名称进行装配

Service层:

@Service()
public class IocService{

    @Resource
    private IIocDao iiocDao;
    public void add(){
        iiocDao.add();
    }
}

3. @Repository持久层

此注解式持久层组件,用于标注数据访问组件,即DAO组件
DAO层
先定义一个接口

public interface IIocDao{
    public void add();
}

然后实现类

//Dao层中定义了一些接口
//表示将Dao类声明为bean
@Repository
public class IocDao implements IIocDao{
    public void add(){
        System.out.println("调用了Dao");
    }
}
另外一种解释: @Repository对应数据访问层Bean
@Repository(value="userDao")
public class UserDaoImpl extends BeansDaoImpl<User>{
    ......
}

@Repository(value=“userDao”)注解告诉Spring ,让Spring创建一个名字叫做"userDao"的UserDapImpl实例。
当Service需要使用Spring创建的名字叫“userDao”的UserDaoImpl实例时,就可以使用@Resource(name=“userDao”)注解告诉Spring,Spring把创建好的userDao注入给Service即可。

 //注入userDao,从数据库中根据用户Id取出指定用户时需要用到
 @Resource(name = "userDao")
 private BaseDao<User> userDao;

参考文章:https://www.cnblogs.com/xdp-gacl/p/3495887.html

猜你喜欢

转载自blog.csdn.net/qq_41357573/article/details/84454502