5、SpringBoot 配置文件与类绑定:@ConfigurationProperties,@PropertySource指定配置文件,@ImportResource指定Spring的xml配置文件,@Configuration Springboot官方推荐

1、编写要绑定的实体类

@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Boolean happy;
    private Map<String,Object> maps;
    private List<String> lists;
    private Dog dog;

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", happy=" + happy +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}

2、编写application.yml

person:
  name: edwin
  happy: true
  maps: {k1: v1,k2: v2}
  lists: [aaa,bbb,ccc]
  dog:
    name: wangcai
    age: 22

3、还需要添加一个依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

 4、使用@PropertySource注解指定一个自己定义的配置文件person.properties

@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
public class Person {

    private String lastName;
    private Integer age;
}
person.lastName=222222
person.age=33

5、使用@ImportResource(locations = {"classpath:beans.xml"}) 加载一个指定的Spring xml的配置文件

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class Swagger2Application {

    public static void main(String[] args) {
        SpringApplication.run(Swagger2Application.class, args);
    }

}
<?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="com.kuang.service.HelloService"></bean>

</beans>

6、sprongboot官方推荐使用@Configuration 全注解的方式添加组件

@Configuration
public class MyAppConfig {

    @Bean
    public HelloService helloService(){
        System.out.println("在soring容器中提及爱你了组件");
        return new HelloService();
    }
}

 

posted @ 2021-06-16 08:34  shunnWcs  阅读(114)  评论(0)    收藏  举报