我也实现 @GlobalAutowired
Spring annotation 提供 @autowired,可以使我们通过注解的方式进行依赖注入,但是这种注入方式比较麻烦,只能逐个注入,没有实现xml配置的 autowire 自动注入功能。
我偶然看到 http://www.iteye.com/topic/263895 实现了 @GlobalAutowired ,我猜想这个 annotation 可以实现对某个类的所有 filed 进行注入。我也尝试的简单实现了一个,下面先看看这个 @GlobalAutowired 使用方法:
@GlobalAutowiredpublic PersonManager{private PersonDao personDao;public List list(){return personDao.list();}}
/** * 全局自动注入 annotation * @author auauau * */@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)public @interface GlobalAutowired {}
/** * 对 classes 中的 field 实现注入 * 目前只实现根据名称注入 * @author auauau * */@Componentpublic 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(); //通过反射取得类中的fieldfor (Field field : fields) {Object o = beanFactory.getBean(field.getName()); //从beanFactory中取得beanif (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;}}