总览
1 @propertySource 注解(更改默认的配置文件,加载某个类中)
2将一个类作为bean添加进去容器之中? @ ImportResource 注解
3 配置文件占位符
github地址 https://github.com/frankg1/springboot-yaml-test
1 @PropertySource 注解
@ConfigurationProperties注解默认是加载全局配置文件,但是不是所有的东西都写在群居配置文件之中(加此注解的类必须是容器组件,所以需要加上@Component)但是在ConfigurationProperties注解之上加上PropertySource注解,就可以吧默认的全局配置文件改成指定配置文件。
在resources目录下新建person.properties配置文件,将配置信息全部放到这里去,那就行了。
- @PropertySource(value={"classpath:person.properties"})
- @Component
- @ConfigurationProperties(prefix = "person")
- public class Person {
- //@Value("${person.name}")
- private String name;
- //@Value("${person.age}")
- private Integer age;
- private boolean boss;
- private Date birth;
- private Map<String,Object> maps;
- private List<Object> lists;
- private Dog dog;
2 如何将一个类作为bean添加进去容器之中? @ ImportResource 注解
首先在resource下创建bean.xml
- <bean id="testBean" class="com.example.springbootyamltest.bean.Dog"></bean>
- <bean id="HelloService" class="com.example.springbootyamltest.service.HelloService" ></bean>
然后在主程序中添加这个注解,标识将这个配置文件加载进来,
@ImportResource(locations = {"classpath:bean.xml"})
但是这不是spring boot推荐的方式 官方推荐的方式如下
推荐使用配置类的方式
新建配置类
- package com.example.springbootyamltest.config;
- import com.example.springbootyamltest.service.HelloService;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- /*
- * @configuration 表名这是一个配置类,来提到之前的xml配置bean的方法
- * xml中使用<bean></bean>这样的方法去配置bean
- * */
- @Configuration
- public class MyConfig {
- @Bean
- //函数名就是bean id
- public HelloService helloService(){
- return new HelloService();
- }
- }
这样就行了,就可以测出来 bean是否被添加到容器之中。
3 配置文件占位符
3.1 随机数
${random.int} random.uuid random.int(10) random.int[1,10]
3.2 如果没有配置,可以使默认值。
${person.name1:noname}