基于Spring进行注解开发
Spring的BeanPostProcessor接口
BeanPostProcessor的作用
Spring容器bean实例化、配置以及其他初始化方法前后,进行一些逻辑处理.就需要实现BeanPostProcessor接口
public interface BeanPostProcessor {
//实例化、依赖注入完毕,在调用显示的初始化之前完成一些定制的初始化任务
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//实例化、依赖注入、初始化完毕时执行
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
声明SpringAnnotationScanner实现BeanPostProcessor接口
public class AutomaticSpringAnnotationsScanner implements BeanPostProcessor {
private static final Logger log = LoggerFactory.getLogger(AutomaticSpringAnnotationsScanner.class);
//注解的集合
private final List<Class<? extends Annotation>> annotations = Arrays.asList(Config.class,Custom.class);
private Class originalBeanClass;
public AutomaticSpringAnnotationsScanner() {
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (this.originalBeanClass != null) {
//得到被注解的对象,保存。执行一些操作
log.info("{} bean listeners added", beanName);
this.originalBeanClass = null;
}
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
final AtomicBoolean add = new AtomicBoolean();
ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
add.set(true);
}
}, new ReflectionUtils.MethodFilter() {
public boolean matches(Method method) {
Iterator i$ = AutomaticSpringAnnotationsScanner.this.annotations.iterator();
Class annotationClass;
do {
if (!i$.hasNext()) {
return false;
}
annotationClass = (Class)i$.next();
} while(!method.isAnnotationPresent(annotationClass));
return true;
}
});
if (add.get()) {
this.originalBeanClass = bean.getClass();
}
return bean;
}
}
自定义的一些注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Config { //自定义的注解,作用在方法上
String value() default "" ;
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Custom {//自定义的注解,作用在方法上
String value() default "";
}
使用
//Springboot的注入方式:在启动的Application类中添加
@Bean
public AutomaticSpringAnnotationsScanner automaticSpringAnnotationsScanner (){
return new SpringAnnotationScanner();
}
//springMvc的注入方式
@Component //声明式注解
public class AutomaticSpringAnnotationsScanner implements BeanPostProcessor{
}
//* 通过配置,或者注解都可以,方式很多