Spring @Autowired field returns null on type of PropertySourcesPlaceholderConfigurer bean object

48 Views Asked by At

my colde below

/* this bean is the bean that alwyas returned as null*/
@Component
public class ContextHolder implements ApplicationContextAware, ServletContextAware {
    
    private static ApplicationContext springContext;
    private static ServletContext servletContext;
    
    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.springContext = applicationContext;
    }
    
    public static ApplicationContext getSpringContext() {
        return springContext;
    }

    public static ServletContext getServletContext() {
        return servletContext;
    }
}


@Component
@PropertySource("classpath:appProps/globals-${spring.profiles.active}.properties")
public class PropertyManager extends PropertySourcesPlaceholderConfigurer {
    @Autowired
    ContextHolder contextHolder; // this binding alwasy return null. I don't know the why
    
    public String get(String key) {
                // NullpointerException occurs, because contextHolder is null
                // But ContextHodler.getSpringContext() static access works, but I want to know
                // why Autowired does not work
        return contextHolder.getSpringContext().getEnvironment().getProperty(key);
    }
}

I want to know why Autowired does not work.

I have search the answer in google. but there no documents about this.

I guess PropertySourcesPlaceholderConfigurer is type of BeanFactoryPostProcessor, So when initialize the PropertySourcesPlaceHolderConfiguer there are no bean of ContextHolder instance in memory, thus contextHolder is null??

0

There are 0 best solutions below