简体   繁体   中英

How to retrieve value normally wired by @Value from WebApplicationContext in a Servlet?

I usually annotate some value fields with @Value , eg

class NotASpringBean {
    @Value("${test.value}")
    String testValue;
}

Note no @Component , no XML entry for this class. That's the reason of trouble. I wire it up with SpringBeanAutowiringSupport.processInjectionBasedOnServletContext

I have to assign the would-have-been value of testValue w/o @Value (or in other words: w/o automatic class processing done by Spring usually).

I have a WebApplicationContext but don't know if it's possible to get the same value that testValue would receive?


To be precise, I have

<context:property-placeholder location="classpath:/props.properties"/>

in my root spring context and I need to access those properties in a Servlet.. and @Value doesn't work. I've worked around it with @Autowired @Qualifier combo, but I had to duplicate properties in XML by defining bean per property.

Also note: I cannot move the properties include to a different file.

  1. Add some.properties to Spring context:

    eg In your config class.

     @Bean public PropertyPlaceholderConfigurer propertyPlaceholder() { PropertyPlaceholderConfigurer bean = new PropertyPlaceholderConfigurer(); bean.setLocations(new ClassPathResource("some.properties")); return bean; } 
  2. You need to retrieve ApplicationContext instance for #3:

    eg

     @Component class HogeContextAware implements org.springframework.context.ApplicationContextAware { @Override public void setApplicationContext(final ApplicationContext applicationContext) { this.global.applicationContext = applicationContext; } } 
  3. Populate a Bean that is not Spring managed:

    eg

     ConfigurableApplicationContext configurableAppContext = (ConfigurableApplicationContext) global.applicationContext.getSpringContext(); YourBean bean = new YourBean(); configurableAppContext.getBeanFactory().autowireBean(bean); bean.getFooValue(); 

It works(, I guess).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM