1.使用@PropertySource加载配置文件
加载自定义配置文件,可以使用@PropertySource和@Configuration注解实现。@PropertySource注解指定自定义配置文件的位置和名称,@Configuration注解可以将实体类指定为自定义配置类。
@Configuration
@PropertySource("classpath:test.properties")
@EnableConfigurationProperties(MyProperties.class)
@ConfigurationProperties(prefix = "test")
public class MyProperties {
private int id;
private String name;
//省略属性的setter()和getter()方法
//省略toString()方法
@Configuration注解用于表示当前类是一个自定义配置类,该类会作为Bean组件添加到Spring容器中,这里等同于@Component注解。
@PropertySource(“classpath:test.properties”)注解指定了自定义配置文件的位置和名称,此示例表示自定义配置文件为classpath类路径下的test.properties文件。
@ConfigurationProperties(prefix = “test”)注解将上述自定义配置文件test.properties中前缀为test的属性值注入到该配置类属性中。
@EnableConfigurationProperties(MyProperties.class)注解表示开启对应配置类MyProperties的属性注入功能,该注解配合@ConfigurationProperties使用。如果自定义配置类使用的是@Component注解而非@Configuration,那么@EnableConfigurationProperties注解就可以省略。
2.使用@ImportResource加载XML配置文件
@ImportResource注解标注一个配置上,通常放置在应用启动类上,使用时需要指定XML配置文件的路径和名称。
例子:
(1) 新建一个com.example.config包。并在该包下创建一个类MyService,该类不需要编写审核代码。
(2) 在resource目录下创建一个名为beans.xml的XML自定义配置文件,在该配置文件中将MyService配置为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.config.MyService" />
</beans>
(3) 编写完XML配置文件后,Spring Boot默认是无法识别的,为了保证XML配置文件生效,需要在项目启动类Chapter02BlogApplication上添加@ImportResource注解来指定Xml文件位置。@ImportResource("classpath:beans.xml")
(4) 在测试类中新增一个测试方法进行输出测试
import org.springframework.context.ApplicationContext;
@Resource
private ApplicationContext applicationContext;
@Test
public void COntextsLoadTest()
{
System.out.println(applicationContext.containsBean("myService"));
}
运行测试方法输出为true表示Spring容器中已经包含了id为myService实例,说明@ImportResource注解成功加载了Spring框架的XML配置文件。
3.使用@Confiuration编写自定义配置
使用@Configuration注解可以指定配置类,它的作用和XML配置是一样的,在默认情况下,使用@Bean注解的方法名就是组件名。
例子:
(1) 在com.example.config包下,新建一个类MyConfig.java。
@Configuration
public class MyConfig {
@Bean
public MyService myService()
{
return new MyService();
}
}
MyConfig是@Configuration注解声明的配置类,该类会被Spring Boot自动扫描识别;使用@Bean注解的myService()方法,其返回值对象会作为组件添加到Spring容器中,并且该组件的id默认是方法名myService。
(2) 将启动类中的@ImportResource注解注释,执行项目测试类中的COntextsLoadTest()方法。运行测试方法输出为true,表示Spring容器中已经包含了id为myService的实例对象组件,说明使用自定义配置类的方法同样可以向Spring容器中添加和配置组件。
本文介绍了SpringBoot中加载配置文件的两种方式:使用@PropertySource加载properties文件,通过@ConfigurationProperties进行属性绑定;使用@ImportResource加载XML配置文件,以及如何通过@Configuration编写自定义配置类。这些方法帮助开发者灵活地管理和配置SpringBoot应用中的组件。
1027





