使用springboot自动配置的特性,自定义起步starter


上一篇文章:https://createdpro.com/back/article/51000351764


上篇文章主要介绍了下springboot自动配置的特性,为了协助理解,我们可以自己定义一个bean交给springboot的自动配置进行注入。


本案例仅存在练习之用,无任何业务能力。



首先创建我们要自动配置的bean的类,这个类有一个销售苹果的业务方法:


package com.test.starter.apple;

import com.test.starter.autoconfig.AppleProperties;

public class SellApple {

private AppleProperties appleProperties;

public SellApple(AppleProperties appleProperties) {
this.appleProperties = appleProperties;
}

public void sell() {
System.out.println(appleProperties.getColor()
+ "色的苹果"
+ appleProperties.getWeight()
+ "斤重,价格是"
+ appleProperties.getPrice());
}

}


然后我们创建AppleProperties这个配置类,我们为每项属性设定了默认值,我们可以通过全局配置文件application.yml进行值得覆盖设置:


package com.test.starter.autoconfig;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "createdpro.apple")
public class AppleProperties {

// 这里设置的值是默认值
// 当使用全局配置文件配置如上前缀时,该值会被覆盖
private Integer weight = 5;

private String color = "red";

private double price = 7.9;

public Integer getWeight() {
return weight;
}

public void setWeight(Integer weight) {
this.weight = weight;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}
}


接下来我们创建HttpClientAutoConfiguration这个类,实现配置的方法:


package com.test.starter.autoconfig;

import com.test.starter.apple.SellApple;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass({SellApple.class})
@EnableConfigurationProperties(AppleProperties.class)
public class AppleAutoConfiguration {

private final AppleProperties appleProperties;

public AppleAutoConfiguration(AppleProperties appleProperties) {
this.appleProperties = appleProperties;
}

@Bean
@ConditionalOnMissingBean(SellApple.class)
public SellApple sellApple() {
return new SellApple(appleProperties);
}

}


接下来创建测试类:


package com.test.stater;

import com.test.stater.apple.SellApple;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {

@Autowired
private SellApple sellApple;

@Test
void sellTest() {
sellApple.sell();
}

}


运行测试方法,发现在应用被启动后,bean被自动配置并创建了。




接下来我们通过全局配置文件application.yml配置一下Apple的属性:


applcation.yml

createdpro:
apple:
weight: 10
color: green


再一次执行测试方法:



配置的默认值已经被覆盖了,使用了我们在全局配置applcation.yml中的值。


spring boot
发布

街角有人祝福,巷口有人哭,这里却没人评论ε=(´ο`*)))