我正在尝试实现自己的BeanPostProcessor实现。
@Component
public class UserDetailsProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof User) {
User user = (User) bean;
List<Annotation> beanAnnotations = Arrays.asList(user.getClass().getAnnotations());
for (Annotation annotation : beanAnnotations) {
UserDetails userDetails = (UserDetails) annotation;
System.out.println(userDetails.firstName());
System.out.println(userDetails.lastName());
}
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
这是我的bean定义:
@SpringBootApplication
public class HelloReactiveApplication {
public static void main(String[] args) {
SpringApplication.run(HelloReactiveApplication.class, args);
}
@Bean
@UserDetails(firstName = "Szymon", lastName = "Nowak")
public User user() {
return new User();
}
}
我正在尝试获取bean的注释,并以某种方式继续它们。我可以清楚地看到user.getClass().getAnnotations()
无法工作的原因,因为它试图从User类获取注释,而不是从bean定义中获取注释。如何获得bean定义的注释列表?
答案 0 :(得分:3)
您应该执行以下操作:
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
BeanDefinition beanDefinition = registry.getBeanDefinition(beanName);
if (beanDefinition instanceof AnnotatedBeanDefinition) {
if (beanDefinition.getSource() instanceof MethodMetadata) {
MethodMetadata beanMethod = (MethodMetadata) beanDefinition.getSource();
String annotationType = UserDetails.class.getName();
if (beanMethod.isAnnotated(annotationType)) {
...
换句话说,即使是@Bean
方法定义,我们也可以通过BeanDefinition
获取所有信息。