SpringBoot自定义参数(6)
一、使用yml配置文件
第一种方式就是把自定义参数配置在yml配置文件中。
例如,在application.yml中加入如下配置。
#自定义参数
define:
userinfo:
username: hzy
department:
name: 研发部门
(1)采用传统的@Value注解注入。注意写法 @Value( "$ { }" )
@Component
@Data
public class Department {
@Value("${define.department.name}")
private String name;
}
(2)采用SpringBoot的@ConfigurationProperties注解注入。指明前缀即可。
@ConfigurationProperties(prefix = "define.userinfo")
@Component
@Data
public class UserInfo {
private String username;
private int age;
private String position;
二、使用Properties配置文件
新建一个配置文件,例如db.properties文件。
database.name = ORACLE database.version = 11
SpringBoot十分贴心的提供了一个@PropertySource注解。只需要指明文件位置即可。
这也分两种注入方式,第一种就是使用@ConfigurationProperties,指明前缀就能省去使用@Value注解。
@PropertySource(value = "classpath:config/db.properties")
@ConfigurationProperties(prefix = "database")
@Component
@Data
public class Database {
private String name;
private String version;
}
第二种就是不用@ConfigurationProperties指明前缀,直接使用@Value注解,配上全名。
@PropertySource(value = "classpath:config/db.properties")
@Component
@Data
public class DatabaseCopy {
@Value("${database.name}")
private String name;
@Value("${database.version}")
private String version;
}

浙公网安备 33010602011771号