Spring annotation 提供 @autowired,可以使我们通过注解的方式进行依赖注入,但是这种注入方式比较麻烦,只能逐个注入,没有实现xml配置的 autowire 自动注入功能。
我偶然看到 http://www.iteye.com/topic/263895 实现了 @GlobalAutowired ,我猜想这个 annotation 可以实现对某个类的所有 filed 进行注入。我也尝试的简单实现了一个,下面先看看这个 @GlobalAutowired 使用方法:
在 class 上声明 @GlobalAutowired 使得 spring 能够自动注入 personDao。
下面看一下处理类
这个处理类通过反射的方式进行注入。目前仅仅实现了按名称注入(byName),还可以进一步扩展,实现按类型注入(byType)。
我偶然看到 http://www.iteye.com/topic/263895 实现了 @GlobalAutowired ,我猜想这个 annotation 可以实现对某个类的所有 filed 进行注入。我也尝试的简单实现了一个,下面先看看这个 @GlobalAutowired 使用方法:
@GlobalAutowired
public PersonManager{
private PersonDao personDao;
public List list(){
return personDao.list();
}
}
在 class 上声明 @GlobalAutowired 使得 spring 能够自动注入 personDao。
/**
* 全局自动注入 annotation
* @author auauau
*
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface GlobalAutowired {
}
下面看一下处理类
/**
* 对 classes 中的 field 实现注入
* 目前只实现根据名称注入
* @author auauau
*
*/
@Component
public class GlobalAutowiredAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor, BeanFactoryAware {
private ConfigurableListableBeanFactory beanFactory;
public Object postProcessBeforeInstantiation(Class beanClass,String beanName) throws BeansException {
return null;
}
public PropertyValues postProcessPropertyValues(PropertyValues pvs,PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
return pvs;
}
/**
* 处理GlobeAutowired
*/
public boolean postProcessAfterInstantiation(Object bean, String beanName)
throws BeansException {
if (bean.getClass().isAnnotationPresent(GlobalAutowired.class)) {
Field[] fields = bean.getClass().getDeclaredFields(); //通过反射取得类中的field
for (Field field : fields) {
Object o = beanFactory.getBean(field.getName()); //从beanFactory中取得bean
if (o != null) {
field.setAccessible(true);
try {
field.set(bean, o); //注入
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return true;
}
/**
* 设定 beanFactory
*/
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
throw new IllegalArgumentException(
"GlobeAutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory");
}
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
}
这个处理类通过反射的方式进行注入。目前仅仅实现了按名称注入(byName),还可以进一步扩展,实现按类型注入(byType)。