java - 如何从 Servlet 中的 WebApplicationContext 检索通常由 @Value 连接的值?

标签 java spring servlets autowired

我通常用 @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 中的属性。

另请注意:我无法将包含的属性移动到其他文件。

最佳答案

  1. 将一些.properties 添加到 Spring 上下文:

    例如在您的配置类中。

    @Bean
     public PropertyPlaceholderConfigurer propertyPlaceholder() {
        PropertyPlaceholderConfigurer bean = new PropertyPlaceholderConfigurer();
        bean.setLocations(new ClassPathResource("some.properties"));
        return bean;
    }
    
  2. 您需要检索 #3 的 ApplicationContext 实例:

    例如

    @Component
    class HogeContextAware implements org.springframework.context.ApplicationContextAware {
        @Override
        public void setApplicationContext(final ApplicationContext applicationContext) {
            this.global.applicationContext = applicationContext;
        }
    }
    
  3. 填充非 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/

相关文章:

java - 还有什么更好的方法来发送响应并以表结构打印数据?

java - 在 Java 中反射(reflect)方法的 Action

java - 按下按钮时使用 ZEST 框架绘制图形不起作用?

java - Struts 2 和 Spring 如何处理 struts 创建的对象

java - 是否可以将 AspectJ 与 MBean 一起使用?

java - 在构建时获取 Maven 属性

java - Servlet 和 JSP 空白

java - 在二维数组中打印字母?第一个字母不显示

java - @Before 和 @AfterReturning 组合可能吗?

multithreading - 我可以从 servlet 生成一个线程吗?