开发者

SpringBoot自动配置实现流程详细分析

开发者 https://www.devze.com 2022-12-13 10:26 出处:网络 作者: 4343
目录第一种第二种第一种 给容器中的组件加上 @ConfigurationProperties注解即可 测试:
目录
  • 第一种
  • 第二种

第一种

给容器中的组件加上

@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 +
                ", seat编程客栈Num=" + 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);
    }
}

控制台结果:

SpringBoot自动配置实现流程详细分析

第二种

第一种的情况下android是自己写的类作为组件,实现自动装配的过程;

但有时候使用第三方类的时候无法将其设置php为自己的组件,所以就需要用

@EnableConfigurationProperties + 开发者_JAVA教程@ConfigurationProperties

将Car类删除@Component注解,此时Car类已经不是组件了:

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

SpringBoot自动配置实现流程详细分析

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

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

标签一样:

SSM中的配置文件中:

    <bean id="car" class="xxx.xxx.xxx.Car">
        <property name="brand" value=""/>
       php <property name="price" value=" "/>
        <property name="seatNum" value=" "/>
www.devze.com    </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自动配置实现流程详细分析的文章就介绍到这了,更多相关SpringBoot自动配置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号