@PropertySource()和@ImportResource()注解说明
@PropertySource() 加载指定配置文件
将指定配置文件中配置、映射的指定类的属性值中、
如:
这是一个类要映射指定配置文件的值到类中
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})//加载person.properties
public class Person {
private String lasName;
private int age;
}
person.properties
person.lasName=小名
person.age=15
测试类
@SpringBootTest
class SpringBoot02QuickApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
测试结果
Person{lasName='小名', age=15}
可以看到将配置文件中的数据加载到了类属性当中‘、
有一个注意点:
就是@ConfigurationProperties(prefix = "person")
这个注解是默认自动映射全局配置文件中的值、如果全局配置文件中没有找到、就会去@PropertySource(value = {"classpath:person.properties"})
中自动匹配值将其映射
如果不加@ConfigurationProperties(prefix = "person")
这个注解就没法自动映射值、就要使用spring中的@value
注解将其一个一个映射
@Component
//@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
public class Person {
@Value("${person.lasName}")
private String lasName;
@Value("${person.age}")
private int age;
}
@ImportResource() 导入spring的配置文件、让配置文件生效
在ssm框架是会有springmvc.xml、application.xml这种配置文件、这个注解就是将xml中配置的东西加载到spring容器当中
看一个例子
通过这个图会发现在spring的上下文中找不到这个bean
现在在主启动类上加上这个注解
在运行程序看看
可以看出springboot将spring的配置文件加载进去了。
小结:注意:
- 这个注解是放在主启动类上的一个注解、放在其他地方无效、
- 这种方式不推荐使用、springboot推荐使用配置类的形式加载bean