对于自定义配置文件,SpringBoot无法识别,需要我们手动加载。
使用@PropertySource加载配置文件
加载自定义配置文件,可以使用@PropertySource 和 @Configuration注解实现
- @PropertySource注解:指定自定义配置文件的位置和名称
- @Configuration注解:将实体类指定为自定义配置类
- 编写自定义配置文件 test.properties,置于全局配置文件同级目录下
# 对实体类对象MyProperties进行属性配置
test.id=10
test.name=test
- 自定义一个配置类MyProperties
- @Configuration注解:表明当前类是一个自定义配置类,该类会作为Bean组件添加到Spring容器中,等同于@Component注解
- @PropertySource(classpath:xxx.properties)注解:指定自定义配置文件的位置和名称
- @ConfigurationProperties(prefix = “test”) :指定配置文件注入属性前缀
- @EnableConfigurationProperties(MyProperties.class): 开启对应配置类的属性注入功能,该注解配合@ConfigurationProperties使用。如果使用@Component注解注入Spring容器,该注解可以省略。
@Configuration
@PropertySource("classpath:test.properties")
@EnableConfigurationProperties(MyProperties.class)
@ConfigurationProperties(prefix = "test")
public class MyProperties {
private int id;
private String name;
...省略set get toString 方法
}
@RunWith(SpringRunner.class)
@SpringBootTest
class Chapter02ApplicationTests {
@Autowired
private Person person;
@Autowired
private MyProperties myProperties;
@Test
void contextLoads() {
System.out.println(myProperties);
}
}
使用@ImportResource加载XML配置文件
传统的Spring项目配置主要基于XML文件。Spring Boot框架不会自动加载到Spring容器中。
如果希望将外部的XML文件加载到程序中,可以使用@ImportSource注解加载配置文件,该注解标注在配置类上,通常置于启动类。
- 新建一个config文件下,创建MyService类
public class MyService {
}
- 在resources目录下创建一个beans.xml文件
- 使用传统的Spring框架XML方式,通过<bean>标签将MyService标注为Spring容器中的Bean组件
<?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="myService" class="com.example.chapter02.config.MyService" />
</beans>
- 在SpringBoot启动类中加入@ImportResource(“classpath:beans.xml”)注解
- 测试效果,得到true,说明Spring容器中已经包含了id为myService的实例
@ImportResource("classpath:beans.xml")
@SpringBootApplication
public class Chapter02Application {
...
}
...
@Autowired
private ApplicationContext applicationContext;
@Test
void contextLoads() {
System.out.println(applicationContext.containsBean("myService"));
}
使用@Configuration编写自定义配置类
在Spring Boot开发中,“约定大于配置”的思想,更推荐使用配置类的方式代替XML配置。
- 编写自定义配置类
- MyConfig是@Configuration声明的配置类(类似声明了一个XML配置文件),该配置类会被SpringBoot自动扫描识别;
- 使用@bean注解的myService()方法,其返回值会作为组件添加到Spring容器中(类似XML配置文件中的<bean>标签配置),并且该组件的默认id是方法名。
@Configuration
public class MyConfig {
@Bean
public MyService myService(){
return new MyService();
}
}