1:在application.properties中读取自定义属性的配置很简单,在这里不做过多的描述:
自定义属性与加载
例如定义如下属性:
com.blog.title=Spring Boot教程
然后通过@Value(“${属性名}”)注解来加载对应的配置属性,具体如下:
@Component
public class BlogProperties {
@Value("${com.blog.title}")
private String title;
// 省略getter和setter
}
参数间的引用
在application.properties中的各个参数之间也可以直接引用来使用,就像下面的设置:
com.blog.title=Spring Boot教程
com.blog.desc=${com.didispace.blog.name}持续更新中
com.blog.desc参数引用了上文中定义的name和title属性。
使用随机数
在一些情况下,有些参数我们需要希望它不是一个固定的值,比如密钥、服务端口等。Spring Boot的属性配置文件中可以通过${random}来产生int值、long值或者string字符串,来支持属性的随机值。
# 随机字符串
com.blog.value=${random.value}
自定义配置文件
在资源文件夹下新建一个redis.properties配置文件,内容如下:
redis.ip=127.0.0.1
redis.port=6379
redis.maxActive=1024
redis.maxIdle=200
redis.maxWait=10000
redis.testOnBorrow=true
redis.testOnReturn=true
redis.maxTotal=600
redis.timeBetweenEvictionRunsMillis=30000
redis.minEvictableIdleTimeMillis=30000
也是为后面整合redis做准备;
然后新建一个实体类,来赋值配置文件的值:
@Configuration
@PropertySource(value = "classpath:redis.properties")
@ConfigurationProperties(prefix = "redis")
public class Redis {
private String ip;
private Integer port;
private String password;
private Integer maxActive;
private Integer maxIdle;
private Long maxWait;
private Boolean testOnBorrow;
private Boolean testOnReturn;
private Integer expire;
private Integer maxTotal;
//省略getter,setter
}
新建一个读取类:
/**
* @Package:com.springboot.utils
* @ClassName:ReadProperties
* @Description:读取自定义配置文件
* @Author Shuyu.Wang
* @Date 2017-12-07 12:18
**/
@EnableConfigurationProperties({Redis.class})
@Component
public class ReadProperties {
@Autowired
private Redis redis;
public void read(){
System.out.println(redis.getIp());
}
}
然后再web类中添加相应的测试接口:
@Autowired
private ReadProperties readProperties;
@RequestMapping(value = "/read",method = RequestMethod.GET)
public String read(){
readProperties.read();
return "over";
}
然后重启工程,访问http://127.0.0.1:8082/boot/read
看到控制台打印了ip:
多个环境配置文件
在现实的开发环境中,我们需要不同的配置环境;格式为application-{profile}.properties,其中{profile}对应你的环境标识,比如:
- application-test.properties:测试环境
- application-dev.properties:开发环境
- application-prod.properties:生产环境
修改application.properties如下:
#根据环境读取配置文件
#application-test.properties:测试环境
#application-dev.properties:开发环境
#application-prod.properties:生产环境
spring.profiles.active=dev
新建application-dev.properties和application-prod.properties,
配置如下:
# Server settings (ServerProperties)
#端口
server.port=8082
server.address=127.0.0.1
#server.sessionTimeout=30
#访问路径名称
server.contextPath=/boot
两个文件中配置不同的port,然后通过更改application.properties的配置来选择哪个配置文件。我本地开发环境是配置的8081,部署环境是8082,application.properties就需要更改端口号来访问服务了。