SpringBoot读取配置文件,赋值给静态变量
方法一:xml通过bean注入
方法二:使用set方法注入
1、配置文件
2、赋值静态变量—注意set函数的写法
@Component
@PropertySource({"classpath:port.properties"})
public class IpPortConfig {
public static String ip;
public static int port;
public static int reStart;
@Value("${demo.ip}")
public void setIp(String ip) {
this.ip = ip;
}
@Value("${demo.port}")
public void setPort(int port) {
this.port = port;
}
@Value("${demo.reStart}")
public void setReStart(int reStart) {
this.reStart = reStart;
}
}
3.属性名和set方法名不必一致
方法三:通过中间变量赋值
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Test {
public static String url = "/dev/xx";
@Value("${url}")
public String tempUrl = "/dev/xx";
@PostConstruct
public void init() {
url = tempUrl;
}
}
评论 (0)