LD is tigger forever,CG are not brothers forever, throw the pot and shine forever.
Modesty is not false, solid is not naive, treacherous but not deceitful, stay with good people, and stay away from poor people.
talk is cheap, show others the code,Keep progress,make a better result.
Survive during the day and develop at night。
目录
概述
Spring中bean的AutowireMode(自动装配模型)和自动装配技术
实现思路分析
1.Spring 注入的方式
spring注入方式有两种: 1 通过set方法 2 通过构造函数(如果有多个构造函数会选择参数多的构造方法)
@Resource: 默认是通过name来查找注入值,如果不存在就报错
@Autowired 通过类型查找(类型),然后再通过name
AutowireMode(自动装配模型):在spring中有四种模式分别是:
1 autowire_no(0): 默认装配模式, 目前非xml配置都是使用这种方式,然后程序员使用注解手动注入
2 autowire_name: 通过set方法,并且 set方法的名称需要和bean的name一致 byName
3 autowire_type: 通过set方法,并且再根据bean的类型,注入属性,是通过类型配置 byType
4 autowire_construcor: 通过构造器注入
demo:
1 首先自定义一个bean注册器,用来设置bean属性的注入方式
public class MyImportBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
GenericBeanDefinition son =
(GenericBeanDefinition)registry.getBeanDefinition("son");
//设置装配模型
//设置auto类型: AUTO_NO 默认是程序要经常加的 @Autowried或者@Resource
//设置Son这个类的属性注入方式为默认类型
son.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_NO);
registry.registerBeanDefinition("son",son);
}
}
2 定义Son这个类
public class Son {
//不做任何处理,这个时候很明显Son对象里面student是空的
private Student student;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
3 测试类:
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new
AnnotationConfigApplicationContext();
applicationContext.register(MyBean.class);
applicationContext.register(Appconfig.class);
applicationContext.refresh();
/* 1 不加 @Autowired或者@Resource 不做特殊处理
* 下面这对象会为空
* 2 写个类实现ImportBeanDenitionRegester, 设置Son属性的注入方式
MyImportBeanDefinitionRegister
*
*
* */
System.out.println("==="+applicationContext.getBean(Son.class).getStudent());
}
}
相关工具如下:
分析:
小结:
主要讲述了一些Spring 注入设计,里面有许多不足,请大家指正~
参考资料和推荐阅读
1.链接: 参考资料.