SpringBoot配置@PropertySource、@ImportResource、@Bean注解
引言
@ConfigurationProperties
- 与@Bean结合为属性赋值
- 与@PropertySource(只能用properties文件)结合读取指定文件
@Validation
- 支持使用JSR303为配置文件进行值校验
@ImportResource
- 读取外部的配置文件
@PropertySource
作用
- 加载指定的配置文件。
在之前我们知道@ConfigurationProperties默认是从全局的配置文件中获取对应的值。但是如果将所有的配置内容都写入到全局配置文件中,会导致配置文件过于大庞大。不理与后期的实际开发中扩展。
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
这个配置文件被成功的注入了应用中。
@ImportResource
作用
- 导入Spring配置文件,让配置文件里面的内容生效;
实例
首先创建一个HelloService类,然后使用传统的配置方式记性IOC的依赖注入,然后测试容器中是否有对应的HelloService的组件
<?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.example.springboot.service.HelloService">
</bean>
</beans>
@Autowired
ApplicationContext ioc;
@Test
public void testHelloService(){
boolean helloService = ioc.containsBean("helloSerice");
System.out.println(helloService);
}
到这里可以看到通过这个方式并没有将对应的组件加入到容器中,自己编写的配置文件也没有自动识别。这个时候就需要使用到@ImportResource注解进行标注
@ImportResource(locations = {"classpath:beans.xml"})
使用这种方式注入组件是成功的
Spring Boot推荐给Spring容器中添加组件的方式就是使用配置类。而且在SpringBoot中推荐使用注解的方式进行组件的注入
使用配置类
一、创建配置类
@Configuration
public class MyConfig {
@Bean
public HelloService helloService(){
System.out.println("配置类来进行组件的注入");
return new HelloService();
}
}
@Configuration表示被标注的类作为一个配置类使用。
@Bean将方法的返回值作为组件添加到容器中;对应的配置ID就是方法的名称,当然也可以通过@Bean的属性值进行制定。
通过配置类的方式也进行了组件的成功注入
其实这里使用的@Configuration和@Bean注解版核心的概念。这个在之前的博客中有提到过关于Spring基于注解的底层原理。