【问题标题】:Unable to load key from the properties file in Spring Boot, null with @Autowired无法从 Spring Boot 中的属性文件加载密钥,@Autowired 为空
【发布时间】:2019-12-30 11:32:35
【问题描述】:

我希望将所有属性文件加载到 List 中,但看起来好像没有工作。我正在关注:https://www.mkyong.com/spring-boot/spring-boot-configurationproperties-example/。我正在使用 Spring Boot v2.2.2.RELEASE。

@Configuration
@PropertySource(value="classpath:endpoints.properties")
public class AppConfig {
    @Value("#{'${endpoints}'.split(',')}")
    private List<String> endpoints;

    public List<String> getEndPoints() {
        return endpoints;
    }
    //To resolve ${} in @Value
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

当我在下面使用它时,我得到了异常。 Environment env 为空。

@Autowired
private Environment env;

@Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
    if(endpoint instanceof MethodEndpoint) {
        MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
        List<String> endpoints = Arrays.asList(env.getProperty("endpoints", String[].class));
        return endpoints.contains(methodEndpoint.getMethod().getName());
    }
    return true;
}

编辑:

@Slf4j
@Component
public class DecisionInterceptor implements EndpointInterceptor {
    @Value("#{'${endpoints}'.split(',')}")
    private List<String> endpoints;

    @Override
    public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
        if(endpoint instanceof MethodEndpoint) {
            MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
//          List<String> endpoints = Arrays.asList(env.getProperty("edr.soap.endpoints", String[].class));
            return endpoints.contains(methodEndpoint.getMethod().getName());
        }
        return true;
    }

    @Override
    public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
        return true;
    }

    @Override
    public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
        return true;
    }

    @Override
    public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
        log.debug("DecisionInterceptor - afterCompletion executed ...");
    }

}

【问题讨论】:

  • 你得到了什么异常?
  • @Environment 为空
  • 你使用Environment env的类是什么Bean?
  • 导入 org.springframework.core.env.Environment;
  • @PAA 看到这个问题了吗,好像是同一个问题:stackoverflow.com/q/54212507/11733759

标签: java spring spring-boot


【解决方案1】:

总结来自 cmets 的响应。 看起来它与this 类似的问题。并且应该检查DecisionInterceptorConfiguration中是如何构造的。

【讨论】:

    猜你喜欢
    • 2014-01-18
    • 1970-01-01
    • 2017-11-17
    • 2015-12-29
    • 1970-01-01
    • 2016-01-05
    • 2019-03-30
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多