前言

上一篇文章讲了如何自定义注解,注解的加载和使用,这篇讲一下Spring的IOC过程,并通过自定义注解来实现IOC。

自定义注解

还是先看一下个最简单的例子,源码同样放在了Github
先定义自己的注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyInject {
}

注入AutowiredAnnotationBeanPostProcessor,并设置自己定义的注解类

@Configuration
public class CustomizeAutowiredTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(CustomizeAutowiredTest.class);
annotationConfigApplicationContext.refresh();
BeanClass beanClass = annotationConfigApplicationContext.getBean(BeanClass.class);
beanClass.print();
}
@Component
public static class BeanClass {
@MyInject
private FieldClass fieldClass;
public void print() {
fieldClass.print();
}
}
@Component
public static class FieldClass {
public void print() {
System.out.println("hello world");
}
}
@Bean
public AutowiredAnnotationBeanPostProcessor getAutowiredAnnotationBeanPostProcessor() {
AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
autowiredAnnotationBeanPostProcessor.setAutowiredAnnotationType(MyInject.class);
return autowiredAnnotationBeanPostProcessor;
} }

运行代码就会发现被*@MyInject修饰的fieldClass被注入进去了。这个功能是借用了Spring内置的AutowiredAnnotationBeanPostProcessor类来实现的。
Spring的IOC主要是通过
@Resource*,@Autowired和*@Inject等注解来实现的,Spring会扫描Bean的类信息,读取并设置带有这些注解的属性。查看Spring的源代码,就会发现其中@Resource是由CommonAnnotationBeanPostProcessor解析并注入的。具体的逻辑是嵌入在代码中的,没法进行定制。
@Autowired*,@Inject是由AutowiredAnnotationBeanPostProcessor解析并注入,观察这个类就会发现,解析注解是放在autowiredAnnotationTypes里面的,所以初始化完成后,调用setAutowiredAnnotationType(MyInject.class) 设置自定义的注解。

	public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.info("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
public void setAutowiredAnnotationType(Class<? extends Annotation> autowiredAnnotationType) {
Assert.notNull(autowiredAnnotationType, "'autowiredAnnotationType' must not be null");
this.autowiredAnnotationTypes.clear();
this.autowiredAnnotationTypes.add(autowiredAnnotationType);
}

同时,这个类实现了InstantiationAwareBeanPostProcessor接口,Spring会在初始化Bean的时候查找实现InstantiationAwareBeanPostProcessor的Bean,并调用接口定义的方法,具体实现的逻辑在AbstractAutowireCapableBeanFactorypopulateBean方法中。
AutowiredAnnotationBeanPostProcessor实现了这个接口的postProcessPropertyValues方法。这个方法里,扫描了带有注解的字段和方法,并注入到Bean。

	public PropertyValues postProcessPropertyValues(
PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass());
try {
metadata.inject(bean, beanName, pvs);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}

扫描的方法如下

	private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
Class<?> targetClass = clazz;
do {
LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
for (Field field : targetClass.getDeclaredFields()) {
Annotation annotation = findAutowiredAnnotation(field);
if (annotation != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
continue;
}
boolean required = determineRequiredStatus(annotation);
currElements.add(new AutowiredFieldElement(field, required));
}
}
for (Method method : targetClass.getDeclaredMethods()) {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
Annotation annotation = BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod) ?
findAutowiredAnnotation(bridgedMethod) : findAutowiredAnnotation(method);
if (annotation != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
continue;
}
if (method.getParameterTypes().length == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should be used on methods with actual parameters: " + method);
}
}
boolean required = determineRequiredStatus(annotation);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
}
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}

注入的方法在AutowiredMethodElementAutowiredFieldElement的*inject()*方法中。

自定义注解注入

AutowiredAnnotationBeanPostProcessor是利用特定的接口来实现依赖注入的。所以自定义的注解注入,也可以通过实现相应的接口来嵌入到Bean的初始化过程中。

  1. BeanPostProcessor会嵌入到Bean的初始化前后
  2. InstantiationAwareBeanPostProcessor继承自BeanPostProcessor,增加了实例化前后等方法

第二个例子就是实现BeanPostProcessor接口,嵌入到Bean的初始化过程中,来完成自定义注入的,完整的例子同样放在Github,第二个例子实现了两种注入模式,第一种是单个字段的注入,用*@MyInject注解字段。第二种是使用@FullInject注解,会扫描整理类的所有字段,进行注入。这里主要说明一下@FullInject*的实现方法。

  1. 定义FullInject
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FullInject {
}
  1. JavaBean
	public static class FullInjectSuperBeanClass {
private FieldClass superFieldClass;
public void superPrint() {
superFieldClass.print();
}
}
@Component
@FullInject
public static class FullInjectBeanClass extends FullInjectSuperBeanClass {
private FieldClass fieldClass;
public void print() {
fieldClass.print();
}
}
  1. BeanPostProcessor的实现类
	@Component
public static class MyInjectBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
private ApplicationContext applicationContext;
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (hasAnnotation(bean.getClass().getAnnotations(), FullInject.class.getName())) {
Class beanClass = bean.getClass();
do {
Field[] fields = beanClass.getDeclaredFields();
for (Field field : fields) {
setField(bean, field);
}
} while ((beanClass = beanClass.getSuperclass()) != null);
} else {
processMyInject(bean);
}
return bean;
}
private void processMyInject(Object bean) {
Class beanClass = bean.getClass();
do {
Field[] fields = beanClass.getDeclaredFields();
for (Field field : fields) {
if (!hasAnnotation(field.getAnnotations(), MyInject.class.getName())) {
continue;
}
setField(bean, field);
}
} while ((beanClass = beanClass.getSuperclass()) != null);
}
private void setField(Object bean, Field field) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
try {
field.set(bean, applicationContext.getBean(field.getType()));
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean hasAnnotation(Annotation[] annotations, String annotationName) {
if (annotations == null) {
return false;
}
for (Annotation annotation : annotations) {
if (annotation.annotationType().getName().equals(annotationName)) {
return true;
}
}
return false;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
  1. main 方法
@Configuration
public class CustomizeInjectTest {
public static void main(String[] args) {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
annotationConfigApplicationContext.register(CustomizeInjectTest.class);
annotationConfigApplicationContext.refresh();
FullInjectBeanClass fullInjectBeanClass = annotationConfigApplicationContext.getBean(FullInjectBeanClass.class);
fullInjectBeanClass.print();
fullInjectBeanClass.superPrint();
}
}

这里把处理逻辑放在了postProcessBeforeInitialization方法中,是在Bean实例化完成,初始化之前调用的。这里查找类带有的注解信息,如果带有*@FullInject*,就查找类的所有字段,并从applicationContext取出对应的bean注入到这些字段中。

结语

Spring提供了很多接口来实现自定义功能,就像这两篇用到的BeanFactoryPostProcessorBeanPostProcessor,这两个主要是嵌入到BeanFactory和Bean的构造过程中,他们的子类还会有更多更精细的控制。

深入Spring:自定义IOC的更多相关文章

  1. 死磕Spring之IoC篇 - 解析自定义标签(XML 文件)

    该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读 Spring 版本:5.1. ...

  2. Spring源码-IOC部分-自定义IOC容器及Bean解析注册【4】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  3. spring的IOC和AOP

     spring的IOC和AOP 1.解释spring的ioc? 几种注入依赖的方式?spring的优点? IOC你就认为他是一个生产和管理bean的容器就行了,原来需要在调用类中new的东西,现在都是 ...

  4. 挖坟之Spring.NET IOC容器初始化

    因查找ht项目中一个久未解决spring内部异常,翻了一段时间源码.以此文总结springIOC,容器初始化过程. 语言背景是C#.网上有一些基于java的spring源码分析文档,大而乱,乱而不全, ...

  5. 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器

    web.xml中的加载顺序为:listener > filter > servlet > spring. 其中filter的执行顺序是filter-mapping在web.xml中出 ...

  6. Spring对IOC的理解

    一.IOC控制反转和DI依赖注入 1.控制反转,字面可以理解为:主动权的转移,原来一个应用程序内的对象是类通过new去主动创建并实例化的,对对像创建的主动权在程序代码中.程序不仅要管理业务逻辑也要管理 ...

  7. (转)java之Spring(IOC)注解装配Bean详解

    java之Spring(IOC)注解装配Bean详解   在这里我们要详细说明一下利用Annotation-注解来装配Bean. 因为如果你学会了注解,你就再也不愿意去手动配置xml文件了,下面就看看 ...

  8. Spring 的IOC和AOP总结

    Spring 的IOC和AOP IOC 1.IOC 许多应用都是通过彼此间的相互合作来实现业务逻辑的,如类A要调用类B的方法,以前我们都是在类A中,通过自身new一个类B,然后在调用类B的方法,现在我 ...

  9. 【死磕 Spring】----- IOC 之解析 bean 标签:开启解析进程

    原文出自:http://cmsblogs.com import 标签解析完毕了,再看 Spring 中最复杂也是最重要的标签 bean 标签的解析过程. 在方法 parseDefaultElement ...

随机推荐

  1. 一网打尽 @ExceptionHandler、HandlerExceptionResolver、@controlleradvice 三兄弟!

    把 @ExceptionHandler.HandlerExceptionResolver.@controlleradvice 三兄弟放在一起来写更有比较性.这三个东西都是用来处理异常的,但是它们使用的 ...

  2. Linux就该这么学07学习笔记

    参考链接:https://www.linuxprobe.com/chapter-07.html RAID磁盘冗余阵列 RAID 0 RAID 0技术把多块物理硬盘设备(至少两块)通过硬件或软件的方式串 ...

  3. MySQL的安装及简单调优

    MySQL的安装及调优 1. 安装注意点 ubuntu18的安装方式 sudo apt-get update sudo apt-get install -y mysql-server mysql-cl ...

  4. Splay平衡树入门小结

    学习到这部分算是数据结构比较难的部分了,平衡树不好理解代码量大,但在某些情况下确实是不可替代的,所以还是非学不可. 建议先学Treap之后在学Splay,因为其实Splay有不少操作和Treap差不多 ...

  5. 太恐怖了!黑客正在GPON路由器中利用新的零日漏洞

    即使在意识到针对GPONWi-Fi路由器的各种主动网络攻击之后,如果您还没有将其从互联网上带走,那么请小心,因为一个新的僵尸网络已加入GPON组织,该组织正在利用未公开的零日漏洞(零时差攻击). 来自 ...

  6. 安装RabbitMQ服务器及基本配置

    RabbitMQ是一个在AMQP协议标准基础上完整的,可复用的企业消息系统.它遵循Mozilla Public License开源协议,采用 Erlang 实现的工业级的消息队列(MQ)服务器,Rab ...

  7. spring微服务(顺序由简入难易于理解)

    一.为微服务应用增加健康监控 1.在 build.gradle 文件 dependencies 属性中增加 compile('org.springframework.boot:spring-boot- ...

  8. Delphi Treeview 用法(概念、属性、添加编辑插入节点、定位节点、拖拽等)

    今天再细研究了一下Treeview的用法,网上虽然总结了很多,但是还是有很多节点没有讲到了,也给使用中遇到很多问题.特地总结一下: 1.概念 Treeview用于显示按照树形结构进行组织的数据.Tre ...

  9. 深度学习中的batch、epoch、iteration的含义

    深度学习的优化算法,说白了就是梯度下降.每次的参数更新有两种方式. 第一种,遍历全部数据集算一次损失函数,然后算函数对各个参数的梯度,更新梯度.这种方法每更新一次参数都要把数据集里的所有样本都看一遍, ...

  10. xshell如何传输文件【转】

    1.打开xshell工具,连接到服务器. 2.yum安装一款工具. #yum install  lrzsz -y 3.检查是否安装成功. #rpm -qa |grep lrzsz 4.上传文件的执行命 ...