SpringBoot学习–使用配置文件对静态变量赋值
搭建SpringBoot环境
建立maven项目。向pom.xml文件引入相关包
<!--spring-boot 依赖的父工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
添加主函数
在根目录添加Appilcation.java启动类
package com.pzr.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.pzr.demo.staticclass.Properties;
/**
* 启动类
* @author ASUS
*
*/
@SpringBootApplication
public class Appilcation {
public static void main(String args[]){
SpringApplication.run(Appilcation.class, args);
System.out.println("使用端口:"+Properties.port);
}
}
添加配置文件
在src/main/resources添加配置文件application.properties
添加上开发环境(application-dev.properties),生产环境(application-prod.properties),测试环境(application-test.properties)的配置文件
application.properties文件,说明使用prod后缀的配置文件
spring.profiles.active=prod
application-dev.properties文件
server.port=8080
application-prod.properties文件
server.port=8081
application-test.properties文件
server.port=8082
配置文件类
本文是使用@Value注解为静态变量赋值
注意:
- 配置文件类必须使用@Component注解,纳入到容器管理中来。
- 使用@Value为set方法注解,set方法不使用static进行修饰。
配置文件类Properties.java
package com.pzr.demo.staticclass;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Properties {
public static String port;
@Value("${server.port}")
public void setPort(String port) {
Properties.port = port;
}
}
结果
通过主配置文件application.properties切换不同环境的配置文件如:spring.profiles.active=prod则是使用application-prod.properties文件中的配置,控制台会打印“使用端口:8081”