2016-08-23 11 views
0

私自身のBeanPostProcessorインプリメンテーションを実装しようとしています。BeanPostProcessorインプリメンテーションのBeanアノテーションを取得

@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(); 
    } 
} 

私は豆の注釈を取得し、何とかそれを続行しようとしています。私は明らかになぜuser.getClass().getAnnotations()が動作しないのかを見ることができます。なぜなら、Bean定義からのアノテーションではなく、Userクラスからアノテーションを取得しようとするからです。どのようにしてBean定義のアノテーションのリストを取得できますか?それは我々がそのBeanDefinition経由ですべての情報を取得することができます@Beanメソッドの定義がある場合でも、他の言葉で

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)) { 
    ... 

+0

あなたは実際にその注釈で何をしようとしていますか? –

+0

この例では、フィールド( 'System.out.println(userDetails.firstName());'、System.out.println(userDetails.lastName());)を出力したいだけですが、後でこれを設定したいと思いますbeanの値 – nowszy94

+0

実際、BeanPostProcessorを使ってカスタム注釈を実装する方法を学びたいだけです – nowszy94

答えて

1

あなたのような何かをする必要があります。

+0

ありがとうございます。それは私が手に入れたいものです。 – nowszy94

+0

もう1つ。 Annotationのインスタンスを取得することは可能ですか?私はそれを私のカスタムアノテーション( 'UserDetails')にキャストできますか? '\t \t \t \t \t beanMethod.getAllAnnotationAttributes()'のようにしますが、そのマップの代わりにAnnotationクラスとして – nowszy94

+1

AnnotatedElementUtils.getMergedAnnotation() '? –

関連する問題