天天看点

Spring完整揭秘(四):Spring的IoC容器之基于注解的自动装配

文章目录

  • ​​背景​​
  • ​​classpath-scanning​​
  • ​​注解​​
  • ​​@Autowired​​
  • ​​使用 @PostConstruct​​
  • ​​完整测试​​

背景

  • 在​​《Spring的IoC容器之BeanFactory》​​​与​​Spring的IoC容器之ApplicationContext​​两篇文章中,我们在xml文件中配置bean标签,实现了依赖注入,本文将介绍基于注解的方式实现自动装配。

classpath-scanning

  • 在前面的示例中我们需要将相应对象的bean定义,一个个地添加到IoC容器的配置文件中,如果bean的数量越来越多,配置文件会变得非常庞大(虽然我们可以将一个文件分解成多个文件)且容易出错,为了解决这个问题,Spring引入了classpath-scanning的功能:
使用相应的注解对组成应用程序的相关类进行标注之后,classpath-scanning功能可以从某一顶层包(base package)开始扫描。当扫描到某个类标注了相应的注解之后,就会提取该类的相关信息,构建对应的 BeanDefinition ,然后把构建完的 BeanDefinition注册到容器中。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <description>SpringIoc</description>

    <context:component-scan base-package="com"/>
    
</beans>      
  • context:component-scan 将遍历扫描 com包下的所有类型定义,寻找标注了相应注解的类,并添加到IoC容器。
注解
  • Spring可以在类路径下寻找以下注解的组件:
  1. @Service:用于标注业务层组件
  2. @Controller :标注控制层组件
  3. @Repository 标注数据访问组件
  4. @Components 泛指组件,当组件不好归类的时候,可以用这个注解
/**
 * 使用 @Component 标注的Food类
 *
 * @author zhuhuix
 * @date 2020-07-30
 */
@Component
public class Food {
    // 类型
    private String foodType;
    // 名称
    private String foodName;
    // 数量
    private int foodNum;

    public Food(){
        System.out.println("Food对象创建");
    }

    public Food(String foodType, String foodName, int foodNum) {
        this.foodType = foodType;
        this.foodName = foodName;
        this.foodNum = foodNum;
    }

    public String getFoodType() {
        return foodType;
    }

    public void setFoodType(String foodType) {
        this.foodType = foodType;
    }

    public String getFoodName() {
        return foodName;
    }

    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }

    public int getFoodNum() {
        return foodNum;
    }

    public void setFoodNum(int foodNum) {
        this.foodNum = foodNum;
    }

    @Override
    public String toString() {
        return "com.Food{" +
                "foodType='" + foodType + '\'' +
                ", foodName='" + foodName + '\'' +
                ", foodNum=" + foodNum +
                '}';
    }
}      

@Autowired

  • @Autowired 是基于注解的依赖注入的核心注解,它的存在可以让容器知道需要为当前类注入哪些依赖。
/**
 * 使用@Autowired实现依赖注入
 * 
 * @author zhuhuix
 * @date 2020-08-04
 */
@Component
public class Student {
    private String name;
    @Autowired
    private Food food;

    public Student() {
        System.out.println("Student对象创建");
    }

    public void haveLunch(){
        System.out.println(this.name+"进食午餐:"+this.food.toString());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Food getFood() {
        return food;
    }

    public void setFood(Food food) {
        this.food = food;
    }
}      
  • 自动配置一般而言说的是spring的@Autowired,是spring的特性之一,我们可以看一下此注解的源码:
* @author Juergen Hoeller
 * @author Mark Fisher
 * @author Sam Brannen
 * @since 2.5
 * @see AutowiredAnnotationBeanPostProcessor
 * @see Qualifier
 * @see Value
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

  /**
   * Declares whether the annotated dependency is required.
   * <p>Defaults to {@code true}.
   */
  boolean required() default true;

}      
  • 在该源码中,提到了需参考AutowiredAnnotationBeanPostProcessor类:
public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,
    MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
// 构造函数
public AutowiredAnnotationBeanPostProcessor() {
    // 支持@Autowired注解
    this.autowiredAnnotationTypes.add(Autowired.class);
    // 支持@Value注解
    this.autowiredAnnotationTypes.add(Value.class);
    try {
      this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
          ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
      logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
    }
    catch (ClassNotFoundException ex) {
      // JSR-330 API not available - simply skip.
    }
  }
  ...
}      
  • 感兴趣地可以跟踪AutowiredAnnotationBeanPostProcessor类中postProcessMergedBeanDefinition这个过程:
@Override
  public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
    InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
    metadata.checkConfigMembers(beanDefinition);
  }
  ...      
使用 @PostConstruct
  • @PostConstruct 不是服务于依赖注入的,它们主要用于标注对象生命周期管理相关方法,这与Spring的 InitializingBean 和 DisposableBean 接口,以及配置项中的init-method 和 destroy-method 起到类似的作用:
/**
 * 使用@Autowired实现依赖注入
 *
 * @author zhuhuix
 * @date 2020-08-04
 */
@Component
public class Student {
    private String name;
    @Autowired
    private Food food;

    public Student() {
        System.out.println("Student对象创建");
    }

    @PostConstruct
    public void setFood() {
        this.food.setFoodType("面食");
        this.food.setFoodName("阳春面");
        this.food.setFoodNum(1);
    }

    public void haveLunch(){
        System.out.println(this.name+"进食午餐:"+this.food.toString());
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Food getFood() {
        return food;
    }


}      

完整测试

/**
 * 自动装配测试
 *
 * @author zhuhuix
 * @date 2020-08-04
 */
public class ApplicationAutowired {
    
    public static void main(String[] args) {
        // 自动扫描包
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-autowired.xml");

        // 加载食物对象
        Food food = (Food) applicationContext.getBean("food");
        food.setFoodType("面食");
        food.setFoodName("阳春面");
        food.setFoodNum(1);

        // 加载学生对象
        Student student = (Student)applicationContext.getBean("student");
        student.setName("Jack");
        student.haveLunch();

    }
}