欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot自動(dòng)配置實(shí)現(xiàn)流程詳細(xì)分析

 更新時(shí)間:2022年12月12日 11:31:26   作者:4343  
這篇文章主要介紹了SpringBoot自動(dòng)配置原理分析,SpringBoot是我們經(jīng)常使用的框架,那么你能不能針對(duì)SpringBoot實(shí)現(xiàn)自動(dòng)配置做一個(gè)詳細(xì)的介紹。如果可以的話,能不能畫一下實(shí)現(xiàn)自動(dòng)配置的流程圖。牽扯到哪些關(guān)鍵類,以及哪些關(guān)鍵點(diǎn)

第一種

給容器中的組件加上

@ConfigurationProperties注解即可

測(cè)試:

@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 對(duì)象自動(dòng)配置。

運(yùn)行:

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);
    }
}

控制臺(tái)結(jié)果:

第二種

第一種的情況下是自己寫的類作為組件,實(shí)現(xiàn)自動(dòng)裝配的過程;

但有時(shí)候使用第三方類的時(shí)候無(wú)法將其設(shè)置為自己的組件,所以就需要用

@EnableConfigurationProperties + @ConfigurationProperties

將Car類刪除@Component注解,此時(shí)Car類已經(jīng)不是組件了:

11 usages
@ConfigurationProperties(prefix = "mycar " )
public class Car {
3 usages
private String brand ;
3 usages
private Integer price ;
3 usages

此時(shí),假設(shè)Car是第三方提供的類:

對(duì)于第三方的類 想要其作為組件就需要@Bean注解,就和之前的SSM項(xiàng)目中配置的bean

標(biāo)簽一樣:

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;
    }
}

控制臺(tái)顯示結(jié)果一樣:

到此這篇關(guān)于SpringBoot自動(dòng)配置實(shí)現(xiàn)流程詳細(xì)分析的文章就介紹到這了,更多相關(guān)SpringBoot自動(dòng)配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論