Spring autowired bean for @Aspect aspect is null

后端 未结 9 1064
离开以前
离开以前 2020-11-29 03:42

I have the following spring configuration:





        
9条回答
  •  一整个雨季
    2020-11-29 04:00

    Configuring @Autowired with java config only (so no XML based configuration) requires a bit of extra work than just adding @Configuration to the class, as it also needs the aspectOf method.

    What worked for me was creating a new class:

    @Component
    public class SpringApplicationContextHolder implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext = null;
    
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
           this.applicationContext = applicationContext;
        }
    }
    

    And then use that in you aspect in conjunction with using @DependsOn @Configured and @Autowired:

    @DependsOn("springApplicationContextHolder")
    @Configuration
    @Aspect
    public class SomeAspect {
    
        @Autowired
        private SomeBean someBean;
    
        public static SomeAspect aspectOf() {
            return SpringApplicationContextHolder.getApplicationContext().getBean(SomeAspect.class);
        }
    

    The @DependsOn is needed because spring can't determine the dependency because the bean is used staticly.

提交回复
热议问题