前言
上一篇文章講了如何自定義注解耍共,注解的加載和使用苗傅,這篇講一下Spring的IOC過程滑潘,并通過自定義注解來實現(xiàn)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;
}
}
運行代碼就會發(fā)現(xiàn)被@MyInject修飾的fieldClass被注入進去了霜威。這個功能是借用了Spring內置的AutowiredAnnotationBeanPostProcessor類來實現(xiàn)的谈喳。
Spring的IOC主要是通過@Resource,@Autowired和@Inject等注解來實現(xiàn)的戈泼,Spring會掃描Bean的類信息婿禽,讀取并設置帶有這些注解的屬性赏僧。查看Spring的源代碼,就會發(fā)現(xiàn)其中@Resource是由CommonAnnotationBeanPostProcessor解析并注入的扭倾。具體的邏輯是嵌入在代碼中的淀零,沒法進行定制。
而@Autowired膛壹,@Inject是由AutowiredAnnotationBeanPostProcessor解析并注入,觀察這個類就會發(fā)現(xiàn)驾中,解析注解是放在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);
}
同時,這個類實現(xiàn)了InstantiationAwareBeanPostProcessor接口链方,Spring會在初始化Bean的時候查找實現(xiàn)InstantiationAwareBeanPostProcessor的Bean持痰,并調用接口定義的方法,具體實現(xiàn)的邏輯在AbstractAutowireCapableBeanFactory的populateBean方法中。
AutowiredAnnotationBeanPostProcessor實現(xiàn)了這個接口的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);
}
注入的方法在AutowiredMethodElement和AutowiredFieldElement的inject()方法中移剪。
自定義注解注入
AutowiredAnnotationBeanPostProcessor是利用特定的接口來實現(xiàn)依賴注入的。所以自定義的注解注入薪者,也可以通過實現(xiàn)相應的接口來嵌入到Bean的初始化過程中纵苛。
- BeanPostProcessor會嵌入到Bean的初始化前后
- InstantiationAwareBeanPostProcessor繼承自BeanPostProcessor,增加了實例化前后等方法
第二個例子就是實現(xiàn)BeanPostProcessor接口,嵌入到Bean的初始化過程中言津,來完成自定義注入的攻人,完整的例子同樣放在Github,第二個例子實現(xiàn)了兩種注入模式悬槽,第一種是單個字段的注入怀吻,用@MyInject注解字段。第二種是使用@FullInject注解初婆,會掃描整理類的所有字段蓬坡,進行注入。這里主要說明一下@FullInject的實現(xiàn)方法磅叛。
- 定義FullInject
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FullInject {
}
- 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();
}
}
- BeanPostProcessor的實現(xiàn)類
@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;
}
}
- 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提供了很多接口來實現(xiàn)自定義功能慰安,就像這兩篇用到的BeanFactoryPostProcessor和BeanPostProcessor,這兩個主要是嵌入到BeanFactory和Bean的構造過程中坝橡,他們的子類還會有更多更精細的控制泻帮。