SpringBoot | 配置文件的注入(二)

1. 使用@PropertySource

使用 @PropertySource 注解可以从外部加载指定的配置文件,将配置文件与 JavaBean 相绑定,使 JavaBean 读取配置文件中的值

在类路径下创建一个 people.properties 文件

people.last-name=张三三
people.age=100
people.birth=2019/2/3
people.boss=false
people.maps.password=lwh123
people.maps.address=xxx
people.lists=a,b,c,d,e
people.dog.name=dog
people.dog.age=19

在 Bean 在绑定该配置文件

@Component
@ConfigurationProperties(prefix = "people")    // 对应配置文件中的前缀
@PropertySource(value = {"classpath:people.properties"})    // 指定从类路径下的 people.properties 文件获取配置文件的值
public class People {

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String, String> maps;
    private List<String> lists;
    private Dog dog;

    // 省略 getter/setter 方法
    
    // 省略 toString 方法
}

这里的 @ConfigurationProperties(prefix = 'people') 指定了配置文件中使用的前缀,对应配置文件中的 people.xxx 配置项,而 @PropertySource(value = {"classpath:xxx}") 则指定了从类路径下获取配置文件的信息

2. 使用@ImportResourse

使用@ImportResourse 注解可以导入 Spring 的配置文件,让配置文件里面的配置生效

先准备一个 Spring 的配置文件 beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="helloService" class="edu.just.springboot.service.HelloService"></bean>

</beans>

如果没有进行其他配置,那么该 Spring 的配置文件也是不会生效的,如果想让配置文件生效,需要在主程序类上加上 @ImportResource(locations = ...) 注解

@ImportResource(locations = {"classpath:beans.xml"})    // 导入类路径下的 Spring 配置文件
@SpringBootApplication
public class Springboot02ConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(Springboot02ConfigApplication.class, args);
    }
}

但是在实际开发中不可能为每一个组件都单独配置一个 xxx.xml 文件,然后再使用注解的方式进行导入,这样过于麻烦

SpringBoot 中推荐使用配置类的方法给容器中添加组件

新建一个配置类 MyApplicationConfig

@Configuration
public class MyApplicationConfig {
    @Bean
    public HelloService helloService() {
        System.out.println("helloService组件");
        return new HelloService();
    }
}

其中的 @Configuration 注解用来指名当前类是一个配置类,替代 Spring 的 xml 配置文件,@Bean 注解类似于之前 Spring 配置文件中的 <bean><bean/> 标签。

这里我将 HelloService 方法的返回值添加到 Spring 的容器中,该组件的默认 id 就是方法的名字,即 helloService

猜你喜欢

转载自blog.csdn.net/babycan5/article/details/85961474