1.@PropertySource
@PropertySource的作用是从指定的配置文件中读取配置信息,而@ConfigurationProperties是从全局配置文件中获取配置信息。显然不能把所有的配置信息都写在全局配置文件中,这时候便发挥了@PropertySource的作用。
1.1.新建一个配置文件
注释掉所有的全局配置文件,并新建一个配置文件:person.properties。前面说到SpringBoot的全局配置文件名称是固定的,因此系统会将新建立的配置文件作为局部配置。
1 person.last-name=李四
2 person.age=18
3 person.boss=false
4 person.maps.k1=v1
5 person.maps.k2=14
6 person.lists=a,b,c
7 person.dog.name=dog
8 person.dog.age=15
1.2.修改Person.class文件
1 package com.atguigu.springboot.bean;
2
3 import org.springframework.boot.context.properties.ConfigurationProperties;
4 import org.springframework.context.annotation.PropertySource;
5 import org.springframework.stereotype.Component;
6
7 import java.util.List;
8 import java.util.Map;
9
10 @Component//容器组件
11 @ConfigurationProperties(prefix = "person")
12 @PropertySource(value = {"classpath:person.properties"})
13
14 public class Person {
15 private String lastname;
16 private Integer age;
17 private Boolean boss;
18
19 private Map maps;
20 private List
没有ConfigurationProperties(prefix = "person")则打印出的结果全是null
1.3.单元测试
2.@ImportResource
作用是导入Spring的配置文件
2.1.先创建一个HelloService.class文件
1 package com.atguigu.springboot.service;
2
3 public class HelloService {
4 }
2.2.创建beans.xml
1 xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5
6
7 <bean id="helloService" class = "com.atguigu.springboot.service.HelloService">bean>
8 beans>
这样子,ioc容器中显然没有,事实上我们应该修改一下文件:SpringBoot02ConfigApplication.class
1 package com.atguigu.springboot;
2
3 import org.springframework.boot.SpringApplication;
4 import org.springframework.boot.autoconfigure.SpringBootApplication;
5 import org.springframework.context.annotation.ImportResource;
6
7 @ImportResource(locations = {"classpath:bean.xml"})
8 @SpringBootApplication
9 public class SpringBoot02ConfigApplication {
10
11 public static void main(String[] args) {
12 SpringApplication.run(SpringBoot02ConfigApplication.class, args);
13 }
14
15 }
这样就导入了,每次都新建一个HelloService.class,然后编写beans.xml,最后修改SpringBoot02ConfigApplication.class导入。这个步骤显然太麻烦,SpringBoot推荐给容器中推荐以下方式:
3.@Bean
新建一个配置类
1 package com.atguigu.springboot.config;
2
3 import com.atguigu.springboot.service.HelloService;
4 import org.springframework.context.annotation.Bean;
5 import org.springframework.context.annotation.Configuration;
6
7 /**
8 * //@Configuration注解告诉SpringBoot,这是一个配置类。这样可以代替之前的配置文件beans.xml
9 */
10 @Configuration
11 public class MyAppConfig {
12 @Bean//将方法的返回值添加到ioc中,默认id是方法名
13 public HelloService helloService(){
14 return new HelloService();
15 }
16 }
这个时候SpringBoot02ConfigApplication.class中的@ImportResource(locations = {"classpath:bean.xml"})就没必要存在了。这种方式明显很简单