【问题标题】:Spring Boot Configuration Properties not being set未设置 Spring Boot 配置属性
【发布时间】:2017-09-24 00:51:55
【问题描述】:

我正在尝试在 Spring Boot 环境中设置 clamav 病毒扫描程序。所以我想在属性文件 clamav.properties 中设置主机和端口,该文件与 application.properties 文件一起位于我的资源目录中。它看起来像这样:

clamav.host=localhost
clamav.port=3310
clamav.timeout=1000

我有这门课:

@ConfigurationProperties("clamav.properties")
public class ClamAvClient {

static final Logger logger = LoggerFactory.getLogger(ClamAvClient.class);

@Value("${clamav.host}")
private String clamHost;

@Value("${clamav.port}")
private int clamPort;

@Value("${clamav.timeout}")
private int clamTimeout;

 public boolean ping() throws IOException {
     logger.debug("Host:"+clamHost+" Port:"+clamPort);
     blah.....
 }

private static byte[] asBytes(String s) {
    return s.getBytes(StandardCharsets.US_ASCII);
}   

public String getClamHost() {
    return clamHost;
}

public void setClamHost(String clamHost) {
    this.clamHost = clamHost;
}

public int getClamPort() {
    return clamPort;
}

public void setClamPort(int clamPort) {
    this.clamPort = clamPort;
}

public int getClamTimeout() {
    return clamTimeout;
}

public void setClamTimeout(int clamTimeout) {
    this.clamTimeout = clamTimeout;
}

}

它没有连接,在日志中我得到了这个:

2017-09-23 20:39:45.947 DEBUG 28857 --- [http-nio-8080-exec-2] xxx.ClamAvClient  : Host:null Port:0

所以这些值显然没有设置。我究竟做错了什么?我正在使用 spring-boot-starter-web 的托管版本,我的 Eclipse 说它是 1.4.3-RELEASE

有什么想法吗?

【问题讨论】:

  • 你是如何使用 ping 的?您使用的是@Autowired 版本还是new ClamAvClient().ping() 之类的版本?
  • DOH!!!我正在使用 new ClamAvClient() 这可能是问题所在。
  • 是的,您应该使用带有applicationContext.getBean();@Autowired 注释的自动装配版本。刚刚测试了您提供的代码,它工作正常
  • 使用@ConfigurationProperties("clamav"),参考javabycode.com/spring-framework-tutorial/spring-boot-tutorial/…

标签: java spring spring-boot properties


【解决方案1】:

使用@ConfigurationProperties 将一组属性映射到使用配置处理器的类。

@ConfigurationProperties 中使用@Value 看起来不正确。

你需要将你的属性映射到类是:

@Configuration
@ConfigurationProperties(prefix="clamav")
public class ClamAvClient {

static final Logger logger = LoggerFactory.getLogger(ClamAvClient.class);


private String host;


private int port;


private int timeout;

//getters and setters

}

prefix ="clamav" 与属性文件中的前缀匹配。

host,port,timeout 匹配类的属性。

【讨论】:

  • 我不得不将 clamav.properties 中的属性添加到 application.properties 中,但它成功了。
  • 您仍然可以使用@PropertySource 将其分开以加载您的外部属性
  • 谢谢哥们,到目前为止还没有遇到这个问题,但是有一种新的方法来读取值:) GB
猜你喜欢
  • 2020-11-03
  • 2015-12-21
  • 2019-05-19
  • 1970-01-01
  • 2020-06-14
  • 2016-02-27
  • 1970-01-01
  • 2018-04-28
  • 2020-05-02
相关资源
最近更新 更多