步骤
- 使用@interface 自定义注解
- 编写注解处理类,实现BeanPostProcessor接口
原理
实现BeanPostProcessor接口的类即为Bean后置处理器,Spring加载机制会在所有Bean初始化的时候遍历调用每个Bean后置处理器。
其顺序为:Bean实例化-》依赖注入-》Bean后置处理器-》@PostConstruct
缺陷
只有在会示例化成Bean的类中使用,注解才会生效。(因为是使用了Bean后置处理器实现的嘛)
代码示例
自定义注解接口
import org.springframework.stereotype.Component;
import java.lang.annotation.*;
@Target({ElementType.FIELD}) //声明应用在属性上
@Retention(RetentionPolicy.RUNTIME) //运行期生效
@Documented //Java Doc
@Component
public @interface Boy {
String value() default "";
}
注解处理类
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Com