boot项目中一些秘钥等不常变动的信息大多存储在配置文件中,那么我们怎么获取配置文件中的属性呢?
以获取server端口号为例讲解几种方法;配置信息如下
一:使用@Value注解
@Value("${server.port}")
private String port;
二:使用@ConfigurationProperties注解
@ConfigurationProperties(prefix = "spring.datasource")
public class BootStrap {
private String port;
public void setPort(String port) {
this.port = port;
}
}
三:使用EnvironmentAware接口
public class DatabaseConfiguration implements EnvironmentAware { private static final Logger logger = LoggerFactory.getLogger(DatabaseConfiguration.class); @Resource
private Environment env; private RelaxedPropertyResolver resolver; @Override
public void setEnvironment(Environment environment) {
this.env = environment;
this.resolver = new RelaxedPropertyResolver(environment,"spring.datasource.");
} //用法实例
public void test(){
resolver.getProperty("url");
}
}
到此,本文只记录了三种常用的用法,具体使用哪种还要看项目中哪种方便。