Spring Boot可以使用properties文件、yaml文件或者命令行参数作为外部配置。
1 命令行参数配置
Spring Boot可以基于jar包运行,打成jar包可以通过下面命令运行:
java -jar xxx.jar
可以通过下面命令修改tomcate端口:
java -jar xx.jar --server.port=9090
2 常规属性配置
常规Spring环境下,注入properties文件里的值的方式:
- 通过@PropertySource指明文件位置。
- 通过@Value注入值。
在Spring Boot环境下:
- 在application.properties中定义属性。
- 通过@Value注入值。
3 类型安全的配置(基于properties)
使用@Value这个注入属性在实际开发中有点麻烦,如果多个地方用到这个属性就需要注入多次。
Spring Boot提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联起来。
实战
- 新建Spring Boot项目
- 在pom中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
- 在application.properties中添加配置
author.name=wyh
author.age=30
- 类型安全的Bean
package com.chenfeng.xiaolyuh.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "author")// prefix指定properties的前缀,
public class AuthorSettings {
private String name;
private long age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
}
- 校验代码
package com.chenfeng.xiaolyuh;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.chenfeng.xiaolyuh.properties.AuthorSettings;
@SpringBootApplication // 这个是Spring Boot项目的核心注解,主要是开启自动配置。
@RestController
public class SpringBootStudentApplication {
@Autowired // 通过注解直接注入配置类
private AuthorSettings authorSettings;
@RequestMapping("/")
public String index() {
return "Hello World! " + authorSettings.getName() + "::" + authorSettings.getAge();
}
// 标准的JAVA应用main方法,主要作用作为项目启动的入口
public static void main(String[] args) {
SpringApplication.run(SpringBootStudentApplication.class, args);
}
}