无法从属性文件中使用@Value(“ $ {connection.local}”)获取值

时间:2020-11-03 02:58:06

标签: java spring

我具有这样的属性

connection.local = 0.0.0.0 我在application.properties和application-local.properties上写它是正确还是错误?

但是当我想通过注释获取该值

我使用纯Java来构建应用程序。并使用spring上下文获取值和注释

 @Component
@Scope("singleton")
@Slf4j
@Configuration

public class SocketEngine extends Thread {
    
    /**
     * This is to make sure that the server is running and trying even when
     * idxdatafeed disconnects
     */
    @Value("${connection.local}")
    private String connectionLocalhost;
  
    public void run() {

        while (true) {
            Socket server = null;
            String firstData="xvabv";
            try {
                log.info("Connecting to server " + connectionLocalhost+"!");
                server = new Socket(connectionLocalhost, 9010);
                server.setSoTimeout(10000);
                PrintWriter writer= new PrintWriter(server.getOutputStream());

我对connectionLocal的值是null为什么会这样?

2 个答案:

答案 0 :(得分:0)

您可以通过将值注入构造函数来解决您的问题:

 public SocketEngine(@Value("${connection.local}") String connectionLocalhost) {
    this.connectionLocalhost = connectionLocalhost;

    run();
 }

这应该可以解决问题。但是我真的不知道为什么春天在这里表现出这种(经过测试)。另外,您不需要@Compnent注释,因为@Configuration包含它。

官方方法是在您的配置类中定义以下方法:

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

但这没用,这就是为什么我很困惑!

答案 1 :(得分:0)

我解决了这个问题,添加如下代码。

@PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true)