SpringBoot学习笔记(二) @ImportResource 和 @ConfigurationProperties注解使用和理解
SpringBoot @ImportResource
注解的用法
@ImportResource("classpath:beans.xml")
用途
有的项目比较老旧,采用的xml配置文件的形式注册组件,随着项目的维护更新,我们想将xml文件中的所有组件都使用注解的方式导入容器,但是每一个组件都要对应一个@Bean方法,这样极其麻烦。那么我们如何快速的将组件导入容器中呢?
我们可以将该注解在任意配置类上使用时,这样就可将原来xml配置文件上配置的组件快速导入进容器。
SpringBoot @ConfigurationProperties
注解的用法
@ConfigurationProperties
注解用于属性绑定配置文件配置的值
我们先在yml配置文件写上内容。
mycar:
brand: 宝马
price: 600000
方法一:@Component
+ @ConfigurationProperties
@ConfigurationProperties(prefix = "mycar")
@Component
public class Car {
private String brand;
private Integer price;
}
在其他类上想调用该类时直接使用自动注入就可以。
方法二:@EnableConfigurationProperties
+ @ConfigurationProperties
//1.开启Car配置功能
//2.把这个Car组件自动注册到容器中
@EnableConfigurationProperties(Car.class)
public class MyConfig(){
......
}
调用第三方类时应该使用方法二,因为你没法在别人的类上加 @Component
注解。在其他类上想调用该类时直接使用自动注入就可以。