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

45 篇文章 21 订阅

背景
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);
	}
	...

总体来说,Spring容器启动过程中遇到@Autowired注解,会使用后置处理器机制,来创建属性的对象实例,然后再利用反射机制,将实例化好的属性,赋值到对象上。

使用 @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();

    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智慧zhuhuix

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值