SpringBoot自动配置实现流程详细分析
第一种
给容器中的组件加上
@ConfigurationProperties注解即可
测试:
@Component @ConfigurationProperties(prefix = "mycar") public class Car { private String brand; private Integer price; private Integer seatNum; public Integer getSeatNum() { return seatNum; } public void setSeatNum(Integer seatNum) { this.seatNum = seatNum; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", price=" + price + ", seatNum=" + seatNum + '}'; } public Car() { } }
在application.properties中属性:
mycar.seatNum = 4
mycar.brand = BMW
mycar.price = 100000
即可给之后new 的Car 对象自动配置。
运行:
public class MainApplication { public static void main(String[] args) { //返回springboot中的ioc容器 ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); Car car = run.getBean("car", Car.class); System.out.println(car); } }
控制台结果:
第二种
第一种的情况下是自己写的类作为组件,实现自动装配的过程;
但有时候使用第三方类的时候无法将其设置为自己的组件,所以就需要用
@EnableConfigurationProperties + @ConfigurationProperties
将Car类删除@Component注解,此时Car类已经不是组件了:
11 usages @ConfigurationProperties(prefix = "mycar " ) public class Car { 3 usages private String brand ; 3 usages private Integer price ; 3 usages
此时,假设Car是第三方提供的类:
对于第三方的类 想要其作为组件就需要@Bean注解,就和之前的SSM项目中配置的bean
标签一样:
SSM中的配置文件中:
<bean id="car" class="xxx.xxx.xxx.Car"> <property name="brand" value=""/> <property name="price" value=" "/> <property name="seatNum" value=" "/> </bean>
就等同于SpringBoot中配置类下的:
@Bean public Car car(){ Car car = new Car(); return car; }
其中属性的赋值就需要在Car类上增加
@ConfigurationProperties(prefix = "mycar")注解
最后在该配置类上使用
@EnableConfigurationProperties(Car.class)注解开启即可
@Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(Car.class) public class CarAutoConfiguration { @Bean public Car car(){ Car car = new Car(); return car; } }
控制台显示结果一样:
到此这篇关于SpringBoot自动配置实现流程详细分析的文章就介绍到这了,更多相关SpringBoot自动配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Mybatis工具类JdbcTypeInterceptor运行时自动添加jdbcType属性
今天小编就为大家分享一篇关于Mybatis工具类JdbcTypeInterceptor运行时自动添加jdbcType属性,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2018-12-12Flyway详解及Springboot集成Flyway的详细教程
Flayway是一款数据库版本控制管理工具,,支持数据库版本自动升级,Migrations可以写成sql脚本,也可以写在java代码里。这篇文章主要介绍了Flyway详解及Springboot集成Flyway的详细教程的相关资料,需要的朋友可以参考下2020-07-07SpringBoot集成MyBatisPlus+MySQL的实现
MybatisPlus是国产的第三方插件, 它封装了许多常用的CURDapi,免去了我们写mapper.xml的重复劳动,本文主要介绍了SpringBoot集成MyBatisPlus+MySQL的实现,感兴趣的可以了解一下2023-10-10
最新评论