首页 > 解决方案 > 为什么 bean 中的 Environment 在集成上下文中看不到来自源的属性?

问题描述

在我的 Spring Integration webapp 配置中,我添加了一个属性占位符:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    ...
    xsi:schemaLocation="http://www.springframework.org/schema/context
            ...
            ">

    <ctx:component-scan ... />
    <ctx:annotation-config />
    <mvc:annotation-driven />

    <ctx:property-placeholder location="classpath:config.properties" trim-values="true" />

这是那个文件内容:

apiPath=/requests

我确定此配置有效,因为我已尝试在 http inbound-channel-adapter 中使用该值:

<int-http:inbound-channel-adapter id="/api${apiPath}"
        channel="httpRequestsChannel"
        path="${apiPath}"
        ...>
</int-http:inbound-channel-adapter>

如果我更改属性值,前端应用程序将无法到达端点。

但是,在上下文中,我有一个这样配置的端点:

<int:header-value-router input-channel="httpRequestsChannel" ... >
    <int:mapping value="POST" channel="httpRequestsPostChannel" />
    ...
</int:header-value-router>

<int:channel id="httpRequestsPostChannel" />

<int:chain input-channel="httpRequestsPostChannel">

    <int:transformer method="transform">
        <bean class="transformers.RequestToMessageFile" />
    </int:transformer>

    ...

我想在哪里读取属性值:

public class RequestToMessageFile {

    @Autowired
    private Environment env;

    // ...

    public Message<?> transform(LinkedMultiValueMap<String, Object> multipartRequest) {
        System.out.println("Value: " + env.getProperty("apiPath"));

但在控制台上我看到:

Value: null

我想一旦在 XML 中声明了将成为整个 Web 应用程序环境的一部分的属性源,我错过了什么?我应该在其他地方声明来源吗?

我注意到如果我添加以下注释:

@Configuration
@PropertySource("classpath:config.properties")
public class RequestToMessageFile {

该属性已正确找到,所以我想这只是一个配置问题。

如果它很重要,这里web.xml是配置集成的部分:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/META-INF/spring.integration/context.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
</listener>
<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

更新

部分遵循这个答案,我<ctx:property-placeholder>从 XML 文件中删除,并添加了以下 bean:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:config.properties")
public class WebappConfig {

}

现在 bean 和 XML 文件都可以看到属性。

标签: javaspringspring-integrationspring-environment

解决方案


引用 Martin Deinum 的话:

不,这不是应该如何工作的配置问题。不会向环境添加属性。正如@PropertySource 所做的那样。

因此,您应该<ctx:property-placeholder>从 XML 配置中删除。继续使用@PropertySource("classpath:config.properties")并添加这个 bean 定义:

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

注意它是static如何不要急切地加载所有其他 bean 的@Configuration


推荐阅读