SpringBoot中自动配置
创始人
2024-02-27 07:44:24
0

第一种:

        给容器中的组件加上

@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;}@Overridepublic 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类已经不是组件了:

         此时,假设Car是第三方提供的类:

        对于第三方的类 想要其作为组件就需要@Bean注解,就和之前的SSM项目中配置的bean

标签一样:

        SSM中的配置文件中:

    

        就等同于SpringBoot中配置类下的:

    @Beanpublic Car car(){Car car = new Car();return car;}

        其中属性的赋值就需要在Car类上增加

@ConfigurationProperties(prefix = "mycar")注解

        最后在该配置类上使用

@EnableConfigurationProperties(Car.class)注解开启即可
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(Car.class)
public class CarAutoConfiguration {@Beanpublic Car car(){Car car = new Car();return car;}}

控制台显示结果一样:

 

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...