Spring Boot配置属性未设置

时间:2017-09-24 00:51:55

标签: java spring spring-boot properties

我正在尝试在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

任何想法?

1 个答案:

答案 0 :(得分:2)

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

@Value内使用@ConfigurationProperties看起来并不合适。

您需要将属性映射到该类:

@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匹配该类的属性。