0%

SpringBoot—XML配置文件引入与配置绑定

SpringBoot中除了可以使用配置类来实现组件注册还可以使用传统的配置文件方式来实现。
本文将记录配置文件引入和配置绑定实现组件注册的方法与基本原理。
涉及注解:@ImportResouce,@Component、@ConfigurationProperties、@EnableConfigurationProperties、@Autowired

xml配置文件引入(@ImportResouce)

传统的Spring框架下,我们需要通过xml文件来配置组件并注册,SpringBoot框架中,我们只需要通过在配置类设定@ImportResouce()注解即可实现引入xml配置。
使用方式如表

注解名 使用位置 说明
@ImportResouce(“路径名”) 配置类开头 引入xml配置
注册组件

示例如下:
beans.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

<bean id="haha" class="com.atguigu.boot.bean.User">
<property name="name" value="zhangsan"></property>
<property name="age" value="18"></property>
</bean>

<bean id="hehe" class="com.atguigu.boot.bean.Pet">
<property name="name" value="tomcat"></property>
</bean>
</beans>

配置类:

1
@ImportResource("classpath:beans.xml")

配置绑定

我们习惯于将需要改变的参数配到配置文件,SpringBoot提供了几个注解可以帮助我们快速实现将application.properties的配置绑定。实现方法分为两种。

方法一:@EnableConfigurationProperties + @ConfigurationProperties

这两个注解的使用方法:

注解名 使用位置 说明
@ConfigurationProperties(prefix = “配置前缀”) 从properties引入”配置前缀”的参数
@EnableConfigurationProperties(类名.class) 配置类 1、开启该”类名”的properation配置绑定
2、注册组件到容器
@Autowired 业务类 给组件属性赋值
※此方式创建的组件名为:“类之前缀”-全类名.“类名”

示例:
Car类

1
2
3
4
5
6
@ConfigurationProperties(prefix = "car")
public class Car {
private String name;
private int price;
//get set 构造函数 等等
}

配置类

1
@EnableConfigerationPropties(Car.class)

配置文件,application.properties

1
2
youcar.name = BYD
youcar.price = 1000

测试 Contraller 类

1
2
3
4
5
6
7
8
9
10
11
@RestController
public class HelloController {

@Autowired//自动装配
Car car;

@RequestMapping("/car")
public Car handle01(){
return car;
}
}

方法二:@Component + @ConfigurationProperties

第二个注解用法遇上一个相同,这里 给出第一个用法:

注解名 使用位置 说明
@Component 注册POJO进入容器

※此方式创建的组件名:类名首字母小写

总结

  1. 上述两种方法 @Component@EnableConfigerationProperties(xxx.class) 必须要有一个,用于注册组件
  2. @@ConfigurationProperties(prefix = "xxx"),在配置文件“application.properties”
  3. 业务类需要使用@Autowired实现自动装配属性
  4. 方法选用:看第三方包是否有@Component如果没有,只能用方法一