Spring重温(四)--Spring自动组件扫描

通常情况下,声明所有的Bean类或组件的XML bean配置文件,这样Spring容器可以检测并注册Bean类或组件。 其实,Spring是能够自动扫描,检测和预定义的项目包并实例化bean,不再有繁琐的Bean类声明在XML文件中,这就是我接下来要描述的自动组件装配:

       a.根据以下的4种类型的组件自动扫描注释类型去标识当前类是一个自动扫描组件。

  • @Component – 指示自动扫描组件。
  • @Repository – 表示在持久层DAO组件。
  • @Service – 表示在业务层服务组件。
  • @Controller – 表示在表示层控制器组件。

      注意:无论dao层、service层、控制层都可以用@Component去注解,效果和分别用@Repository、@Service、@Controller一样,我们平常在开发过程中之所以分别注释,只是为了增加代码的可读性。

 
b.AplicatinContext.xml中需加入下面一行配置,这意味着,在 Spring 中启用自动扫描功能。base-package 是指明存储组件,Spring将扫描该文件夹,并找出Bean(注解为@Component)并注册到Spring 容器:
<context:component-scan base-package="**.**.**" />

c.我们平时会配合@Autowired将被此标签注解的类装配到当前类中,如:
package com.yiibai.customer.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yiibai.customer.dao.CustomerDAO;

@Service
public class CustomerService 
{
    @Autowired
    CustomerDAO customerDAO;

    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
        
}

总结:在我们于Spring配置文件中加入<context:component-scan base-package="**.**.**" />的配置,并通过@Repository、@Service、@Controller、@Component等标签进行注解后,Spring能够自动扫描,检测和预定义的项目包并实例化bean。我们在项目的开发中,配合@Autowired 注解通过setter方法、构造函数或字段即可自动装配Bean。注意:

欲开启@Autowired 注解,需要加入<context:annotation-config />在bean配置文件中,或者加入

<bean  class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

原文地址:https://www.cnblogs.com/hedongfei/p/7901032.html