Pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
这块配置就是Spring Boot父级依赖,有了这个,当前的项目就是Spring Boot项目了,spring-boot-starter-parent是一个特殊的starter,它用来提供相关的Maven默认依赖,使用它之后,常用的包依赖可以省去version标签。
Spring Boot提供了很多”开箱即用“的依赖模块,都是以spring-boot-starter-xx作为命名的。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
添加devtools后,修改工程内容后可直接访问,不需要手动重启服务,即热部署。
application.properties
Spring Boot使用了一个全局的配置文件application.properties,放在src/main/resources目录下或者类路径的/config下。Sping Boot的全局配置文件的作用是对一些默认配置的配置值进行修改。
- 系统属性
debug=true
server.port=8081
2.自定义属性
share.url=http://www.gary.com/share_url
然后直接在要使用的地方通过注解@Value(value=”${share.url}”)就可以绑定到你想要的属性上面。如:
@Value(value="${share.url}")
private String shareUrl;
@RequestMapping("/share_url")
public String getShareUrl(){
return shareUrl;
}
3.参数对象
有时候属性太多了,一个个绑定到属性字段上太累,如:
添加配置:
redis.address=127.0.0.1
redis.username=gary
redis.password=123
官方提倡绑定一个对象的bean,这里我们建一个RedisConfigBean.java类,顶部需要使用注解@ConfigurationProperties(prefix = “redis”)来指明使用参数前缀。
package com.gary.configBean;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Data
@ConfigurationProperties(prefix = "redis")
public class RedisConfigBean {
private String address;
private String username;
private String password;
}
然后在application中添加EnableConfigurationProperties注解
@SpringBootApplication
@EnableConfigurationProperties({RedisConfigBean.class})
public class NewSpringBootApplication {
使用时可直接引用:
@Autowired
private RedisConfigBean redisConfigBean;
@RequestMapping("/redis_properties")
public String getRedisProperties(){
return redisConfigBean.toString();
}
参数间引用
redis.info=${redis.username}-${redis.password}
@Value(value="${redis.info}")
private String redisInfo;
@RequestMapping("/redis_info")
public String getRedisInfo(){
return redisInfo;
}
3.多环境配置
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应你的环境标识,比如:
- ·application-dev.properties:开发环境
- ·application-test.properties:测试环境
- ·application-prod.properties:生产环境
至于哪个具体的配置文件会被加载,需要在application.properties文件中通过spring.profiles.active属性来设置,其值对应{profile}值。
如:spring.profiles.active=dev就会加载application-dev.properties配置文件内容
也可以在打完包后,在启动时动态指定配置文件,如:
java -jar .\target\new-spring-boot-1.0-SNAPSHOT.jar --spring.profiles.active=prod