1.先引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.新建一个Java类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* 常量类
*
*/
@Configuration
@ConfigurationProperties(prefix = "constant")
@PropertySource("classpath:constant.properties")
public class Constant {
private String name;
private String sex;
//省略get set toString
}
prefix
代表属性文件中的前缀,@PropertySource
指定加载的那个属性文件,如是默认的application.properties 则不用指定。
//加载多个文件
@PropertySource({
"classpath:config.properties",
"classpath:db.properties" //如果是相同的key,则最后一个起作用
})
springboot 1.5以后的版本,不支持@ConfigurationProperties(prefix = "config2",locations="classpath:test.properties")
locations这种写法,使用@PropertySource
3.新建constant.properties
constant.name=taven
constant.sex=male
4.在启动类添加@EnableConfigurationProperties 指定
@SpringBootApplication
@EnableConfigurationProperties(Constant.class)
public class CommunicateApplication {
public static void main(String[] args) {
SpringApplication.run(CommunicateApplication.class, args);
}
}
使用时,通过依赖注入得到单例
@Autowired
private Constant constant;
网友评论
如:
constant:
name: michael
sex: male