注解@Component、@Controller、@Service、@Repository的区别?

主题:注解@Component、@Controller、@Service、@Repository的区别?

Spring 2.5 中除了提供 @Component 注释外,还提供了几个特殊语义的注释:@Repository、@Service、@Controller。

其实,这三个注释和@Controller是等效的,由于Web应用程序现在采用了三层架构原理,为了层次更加鲜明,降低耦合度,又细分了一下,分别为:持久层、业务层、控制层。

注意:虽然目前这3 个注释和 @Component 相比没有什么新意,但 Spring 将在以后的版本中为它们添加特殊的功能,目的就是方便以后扩展功能。

@Component:泛指组件,当组件不好归类的时候,可以使用这个注解进行标注;

@Controller:用于标注控制层组件;

@Service:用于标注业务层组件;

@Repository:用于标注数据访问组件(持久层),即DAO组件。

  1.  
    @Controller
  2.  
    //为了对url进行分类管理,可以在这里定义根路径,最终访问的url是:根路径+子路径(窄化请求映射)
  3.  
    @RequestMapping("/items" )
  4.  
    public class ItemsController
  5.  
    {
  6.  
    ......
  7.  
    }
  8.  
    @Service
  9.  
    public class LoginServiceImpl implements LoginService
  10.  
    {
  11.  
    ......
  12.  
    }
  13.  
    @Repository
  14.  
    public class LoginDaoImpl implements LoginDao
  15.  
    {
  16.  
    ......
  17.  
    }
Spring2.5为我们引入了组件自动扫描机制,他在类路径下寻找标注了上述注解的类,并把这些类纳入进spring容器中管理。

它的作用和在xml文件中使用bean节点配置组件时一样的。要使用自动扫描机制,我们需要打开以下配置信息:

代码:

  1.  
    <?xml version="1.0" encoding="UTF-8"?>
  2.  
    <beans xmlns="http://www.springframework.org/schema/beans"
  3.  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.  
    xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
  5.  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6.  
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  7.  
    <!--
  8.  
    扫描该package下所有的类、方法、属性上面的注解
  9.  
    -->
  10.  
    <context:component-scan base-package="com.sunhui.iocDemo"></context:component-scan>
  11.  
    </beans>

1、component-scan标签默认情况下自动扫描指定路径下的包(含所有子包),将带有@Component、@Repository、@Service、@Controller标签的类自动注册到spring容器。对标记了 Spring's @Required、@Autowired、JSR250's @PostConstruct、@PreDestroy、@Resource、JAX-WS's @WebServiceRef、EJB3's @EJB、JPA's @PersistenceContext、@PersistenceUnit等注解的类进行对应的操作使注解生效(包含了annotation-config标签的作用)。

2、getBean的默认名称是类名(头字母小写),如果想自定义,可以@Service(“aaaaa”)这样来指定。

这种bean默认是“singleton”的,如果想改变,可以使用@Scope(“prototype”)来改变。

注入方式:

    把DAO实现类注入到action的service接口(注意不要是service的实现类)中,注入时不要new 这个注入的类,因为spring会自动注入,如果手动再new的话会出现错误,然后属性加上@Autowired后不需要getter()和setter()方法,Spring也会自动注入。  

posted on 2022-06-15 17:27  ExplorerMan  阅读(225)  评论(0编辑  收藏  举报

导航