1.application.yml 配置文件
my:
name: forezp
age: 12
number: ${random.int}
uuid: ${random.uuid}
max: ${random.int(10)}
value: ${random.value}
greeting: hi,i'm ${my.name}
读取配置文件内容
@ConfigurationProperties(prefix = "my") //读取配置文件去掉前缀,自动注入 @Component @Data public class ConfigBean { private String name; private int age; private int number; private String uuid; private int max; private String value; private String greeting; } 读取yml 文件 @Value("${my.name}") private String name; @Value("${my.age}") private int age; @RequestMapping(value = "/miya") public String miya(){ return name+":"+age; }
2.配置文件读取properties 文件
test.properties 文件 com.forezp.name=forezp com.forezp.age=12 @Configuration @PropertySource(value = "classpath:test.properties") @ConfigurationProperties(prefix = "com.forezp") @Data public class User { private String name; private String age; }
@PropertySource 注解需要引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
Controller 层使用配置文件类 @RestController @EnableConfigurationProperties({ConfigBean.class, User.class}) public class LucyController { @Autowired ConfigBean configBean; @RequestMapping(value = "/lucy") public String miya(){ return configBean.getGreeting()+">>>>>"+configBean.getName()+">>>>"+configBean.getUuid()+">>>>"+configBean.getMax(); } @Autowired User user; @RequestMapping(value = "/user") public String user(){ return user.getName()+user.getAge(); } }