1 spring自动装配
有关spring中的自动注入,在官网https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-factory-autowire有详细讲解,
自动装配模型分为四种:
no
byType
byName
Construction
1.1 xml配置自动装配
1.1.1 配置全局的自动装配
<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 http://www.springframework.org/schema/context/spring-context.xsd"
default-autowire="byType"
1.1.2 配置单个Bean的自动装配
<bean id="a2Service" class="stu.spring.services.A2Service" autowire="byType"></bean>
- 2 注解配置自动装配
1.2.1 配置全局的自动装配
暂时未找到方法配置,除非修改源码。
1.2.2 配置单个Bean的自动装配
获取AService的BeanDefinition对象,设置BeanDefinition对象的autowireMode属性
@Component
public class CustomerBeanFactoryPostProcesser implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition aService = beanFactory.getBeanDefinition("AService");
GenericBeanDefinition aService1=(GenericBeanDefinition)aService;
System.out.println(aService1.getAutowireMode());
aService1.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);
}
}
2 @Autowire注入
而@Autowire注解注入的方式是先根据类型查找,匹配不到时再根据名称查找,顶多算是半自动注入,通过反射注入的。
给AServer的Bservice属性添加@Autowire注解,在spring启动过程中打断点查看AServer的BeanDefinition对象的属性autowireMode值仍为0,再次表明@Autowire不是自动装配。
3 Spring中注入的方式
构造方法注入
setter方法注入
@Autowire注解比较特殊,是通过反射注入的