意见箱
恒创运营部门将仔细参阅您的意见和建议,必要时将通过预留邮箱与您保持联络。感谢您的支持!
意见/建议
提交建议

如何自定义一个SpringBoot Srarter

来源:恒创科技 编辑:恒创科技编辑部
2024-01-23 07:56:59


前言

上一期我们通过学习知道了自动配置原理,其实创建一个自定义SpringBoot Starter也很简单。


如何自定义一个SpringBoot Srarter

目录

​​如何自定义一个SpringBoot Srarter?​​

​​首先创建一个项目,命名为demo-spring-boot-starter,引入SpringBoot相关依赖​​

​​编写配置文件​​

​​自动装配​​

​​配置自动类​​

​​测试​​


如何自定义一个SpringBoot Srarter?首先创建一个项目,命名为demo-spring-boot-starter,引入SpringBoot相关依赖
        <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

如何自定义一个SpringBoot Srarter_spring

编写配置文件

这里定义了属性配置的前缀

@ConfigurationProperties(prefix = "hello")
public class HelloProperties {

private String name;

//省略getter、setter
}
自动装配

创建自动配置类HelloPropertiesConfigure

@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloPropertiesConfigure {
}
配置自动类

在​​/resources/META-INF/spring.factories​​文件中添加自动配置类路径

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.fighter3.demo.starter.configure.HelloPropertiesConfigure
测试

至此,随手写的一个自定义SpringBoot-Starter就完成了,虽然比较简单,但是完成了主要的自动装配的能力。

创建一个工程,引入自定义starter依赖
        <dependency>
<groupId>cn.fighter3</groupId>
<artifactId>demo-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
在配置文件里添加配置
hello.name=张三
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloTest {
@Autowired
HelloProperties helloProperties;

@Test
public void hello(){
System.out.println("你好,"+helloProperties.getName());
}
}
运行结果

如何自定义一个SpringBoot Srarter_自定义_02

如何自定义一个SpringBoot Srarter_自定义_03

编辑运行结果本期分享到此为止,关注博主不迷路,叶秋学长带你上高速~~


上一篇: POJ-3735 线性变换构造矩阵 下一篇: 手机怎么远程登录云服务器?