Spring Boot (属性、日志、Profile)配置
文章目录
在常规Spring 环境下,注入 properties 文件里的值得方式,通过@PropertySource指明properties 文件的位置,然后通过@Value注入值。在Spring Boot里,我们只需在application.properties定义属性,直接使用@Value注入即可。
添加 application.properties配置文件属性
server.port=9090
server.context-path=/helloworld
jmust.name=lvkun
jmust.age=Hello World
添加配置类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "jmust") //通过@ConfigurationProperties 加载 properties 文件内的配置,通过 prefix 属性指定properties 的配置的前缀,通过location指定properties文件的位置,例如@ConfigurationProperties(prefix = "jmust",location={"classpath:config/jmust.properties"}),当然本例子不需要配置 location
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;
}
}
修改入口类
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.jmust.demo.config.AuthorSettings;
@RestController
@SpringBootApplication
public class DemoApplication {
@Autowired
private AuthorSettings authorSettings; //注入该配置信息
@RequestMapping("/")
public String index(){
return "author name is "+ authorSettings.getName()+" and author age is "+authorSettings.getAge();
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
运行,访问 http://localhost:9090/helloworld
日志配置
Spring Boot 支持Java Util Logging、Log4J、 Log4J2和Logback作为日志框架,默认情况下,Spring Boot 使用Logback作为日志框架
配置日志级别
logging.file=D:/log/log.log
配置日志文件,格式为logging.level.包名=级别:
logging.level.org.springframework.web= DEBUG
Profile 配置
Profilr 是 Spring 用来针对不同环境对不同的配置提供支持的,全局Profile 配置使用 application-{profile}.properties (如 application-prod.properties)
通过在 application.properties 中设置 spring.profiles.active=prod 来指定活动的 Profile。
实例
生产(prod)和开发(dev)环境,生产环境下端口号为80,开发环境下端口号为9090。
生产环境下的配置文件 application-prod.properties:
server.port=80
开发环境下的配置文件 application-dev.properties:
server.port=9090
application.properties中添加:
spring.profiles.active=dev
启动程序结果为:
Registering beans for JMX exposure on startuo
Tomcat started on port(s): 9090 (http)
Started DemoApplication in 2.403 seconds (JVM running for 2.755)
修改application.properties:
spring.profiles.active=prod
启动程序结果为:
Registering beans for JMX exposure on startuo
Tomcat started on port(s): 80 (http)
Started DemoApplication in 2.403 seconds (JVM running for 2.755)