SpringBoot配置文件

    科技2022-08-05  109

    SpringBoot使用一个全局的配置文件,配置文件名是固定的

    application.propertiesapplication.yml

    配置文件的作用:修改springboot自动配置的默认值

    配置属性注入 properties配置

    person.name=叶良辰 person.age=10 person.birth=2020/01/01 person.boss=true person.map.k1=v1 person.map.k2=v2 person.list=a,b,c person.dog.name=jeff person.dog.age=3

    yaml配置

    Person: name: tom age: 8 boss: false birth: 2020/10/7 map: {k1: v1,k2: v2} list: - 苹果 - 华为 - 小米 dog: name: job age: 3

    组件

    /** * 将配置文件中得属性一一映射到组件中 * @ConfigurationProperties: 将yml文件中得属性与此组件绑定 * prefix = "person" :绑定配置文件中的哪一个属性 * @Component:此组件必须加入到容器中,加上此注解 */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String name; private Integer age; private Boolean boss; private Date birth; private Map<String,String> map; private List<String> list; private Dog dog; }

    使用@Value注解属性注入

    /** * 将配置文件中得属性一一映射到组件中 * @ConfigurationProperties: 将yml文件中得属性与此组件绑定 * prefix = "person" :绑定配置文件中的哪一个属性 * @Component:此组件必须加入到容器中,加上此注解 */ @Component //@ConfigurationProperties(prefix = "person") public class Person { @Value("${person.name}") private String name; @Value("#{10*2}") private Integer age; @Value("true") private Boolean boss; private Date birth; private Map<String,String> map; private List<String> list; private Dog dog; }

    @PropertySource 加载指定路径的资源文件;默认是application.properties

    标记在要属性注入的组件上 @PropertySource(value = {“classpath:/person.properties”})

    @ImportResource 导入Spring配置文件,让配置文件的内容生效 SpringBoot不会识别我们自己创建的Spring配置文件,要想Spring配置文件生效,需要在SpringBoot主配置类上加入注解@ImportResource

    @ImportResource(locations = {“classpath:beans.xml”}) 标记在@SpringBootApplication上

    SpringBoot推荐使用配置类的方式添加组件 配置类==Spring配置文件

    /** * @Configuration指明当前类是配置类;用来代替之前的Spring配置文件 * */ @Configuration public class HelloConfig { /* @Bean :返回一个bean组件 id: 方法名helloService */ @Bean public HelloService helloService(){ System.out.println("我被创建了"); return new HelloService(); } }
    Processed: 0.024, SQL: 8