我通常用 @Value
注释一些值字段,例如
class NotASpringBean {
@Value("${test.value}")
String testValue;
}
备注编号 @Component
,此类没有 XML 条目。这就是麻烦的原因。
我用 SpringBeanAutowiringSupport.processInjectionBasedOnServletContext
连接它
我必须分配 testValue
的本来值无@Value
(或者换句话说:通常不由 Spring 完成自动类处理)。
我有一个WebApplicationContext
但不知道是否有可能获得与 testValue
相同的值会收到吗?
准确地说,我有
<context:property-placeholder location="classpath:/props.properties"/>
在我的根 spring 上下文中,我需要访问 Servlet 中的这些属性.. 和 @Value
不起作用。我已经用 @Autowired @Qualifier
解决了这个问题组合,但我必须通过为每个属性定义 bean 来复制 XML 中的属性。
另请注意:我无法将包含的属性移动到其他文件。
最佳答案
将一些.properties 添加到 Spring 上下文:
例如在您的配置类中。
@Bean public PropertyPlaceholderConfigurer propertyPlaceholder() { PropertyPlaceholderConfigurer bean = new PropertyPlaceholderConfigurer(); bean.setLocations(new ClassPathResource("some.properties")); return bean; }
您需要检索 #3 的
ApplicationContext
实例:例如
@Component class HogeContextAware implements org.springframework.context.ApplicationContextAware { @Override public void setApplicationContext(final ApplicationContext applicationContext) { this.global.applicationContext = applicationContext; } }
填充非 Spring 管理的
Bean
:例如
ConfigurableApplicationContext configurableAppContext = (ConfigurableApplicationContext) global.applicationContext.getSpringContext(); YourBean bean = new YourBean(); configurableAppContext.getBeanFactory().autowireBean(bean); bean.getFooValue();
它有效(我猜)。
关于java - 如何从 Servlet 中的 WebApplicationContext 检索通常由 @Value 连接的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501982/