SpringBoot-配置@propertysource,@ImportResources,@bean(五)

@propertysource

我们把所有的配合文件都放到SpringBoot配合文件中有点杂乱,我们可以用注解propertysource来加载指定的配置文件

@propertysource:加载指定的配置文件.

person配置文件

person.name=七月的风
person.age=10
person.lists=小猫,小猪,小狗
person.maps.k1=520
person.maps.k2=1314
person.happy=false
person.birth=2017/6/8
person.cat.name=猫猫
person.cat.age=3

实体类

@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person {
 private String name;
 private  int age;
 private boolean happy;
 private Date birth;
 private Map<String,Object> maps;
 private List<Object> lists;
 private Cat cat;
... }

通过注解@PropertySource也可以加载指定的配置文件.

@ImportResources

@ImportResources:导入Spring的配置文件让配置文件里的值生效.一般呢我们回来Spring的配置文件中添加组件,这种给容器中添加组件的方式SpringBoot并不推荐使用,而SpringBoot推荐的呢是@bean.

@bean

给容器中添加组件,SpringBoot推荐使用全注解的方式.

我们创建一个配置类

//指明当前类是一个配置类
@Configuration
public class MyConfig {
    @Bean  //将方法的返回值添加到容器中,容器中默认的id就是方法的名字,
    public HelloController helloController(){

        System.out.println("给容器中添加组件了");
        return new HelloController();
    }


}

@Configuration:指明当前类是一个配置类

@bean:将方法的返回值添加到容器中,容器中默认的id就是方法的名字.将方法的返回值注册到容器中.