一:读取配置文件涉及的注解
- @Value
使用方式:@value(占位符),例子:@value("${user.name}"),注释在单个变量。
- @PropertySource
配置文件在不声明的情况下application,使用可进行自定义配置文件的设置。
使用方式:@ProperSource(“classpath:配置文件位置”)
例子:SpringBoot项目在resources下有个user.properties,@PropertySource(value={“classpath:/user.properties”})
- @ConfigurationProperties
注释在类上,可声明变量前缀,类中变量会配置文件中属性进行比较
使用方式:@ConfigurationProperties(prefix = “person”)
- 配置文件现状,该项目下存在两个配置文件,一个默认,一个自定义
- application.yml
person.name : 玫瑰
person.age : 18
- user.properties
uer.name=lili
uer.age=30
二:@Value
- 先读默认配置文件
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class Person {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private String age;
}
- 读取自定义的配置文件,添加注解@PropertySource即可
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@PropertySource(value={"classpath:/user.properties"})
public class Person {
@Value("${user.name}")
private String name;
@Value("${user.age}")
private String age;
}
- 结果显示
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class UriControllerTest {
@Autowired
Person person;
@Test
public void test() {
log.info("person:" + person);
}
}
三.@ConfigurationProperties
- 读取默认配置文件
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
private String name;
private String age;
}
- 读取自定义
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "user")
@Component
@PropertySource(value={"classpath:/user.properties"})
public class Person {
private String name;
private String age;
}