spring-boot-starter 自定义
生活随笔
收集整理的這篇文章主要介紹了
spring-boot-starter 自定义
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、新建工程,在官方文檔中命名規(guī)范為? ?xxx-spring-boot-starter? ?xxx為你的starter的項目功能名字
2、在pom.xml文件中加入兩個依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId><version>2.3.3.RELEASE</version> </dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><version>2.3.3.RELEASE</version> </dependency>3、目錄結構如下
4、PersonProperties類
@ConfigurationProperties(prefix = "spring.person") public class PersonProperties {// 姓名private String name;// 年齡private int age;// 性別private String sex = "M";// Getter & Setter?
5、PersonService類
public class PersonService {private PersonProperties properties;public PersonService() {}public PersonService(PersonProperties properties) {this.properties = properties;}public void sayHello(){System.out.println("大家好,我叫: " + properties.getName() + ", 今年" + properties.getAge() + "歲"+ ", 性別: " + properties.getSex());} }6、PersonServiceAutoConfiguration類
首先需要明白下面一張圖的配置內容
@EnableConfigurationProperties:外部化配置
@Configuration? @EnableConfigurationProperties(PersonProperties.class) @ConditionalOnClass(PersonService.class) @ConditionalOnProperty(prefix = "spring.person", value = "enabled", matchIfMissing = true) public class PersonServiceAutoConfiguration {@Autowiredprivate PersonProperties properties;@Bean@ConditionalOnMissingBean(PersonService.class) ?// 當容器中沒有指定Bean的情況下,自動配置PersonService類public PersonService personService(){PersonService personService = new PersonService(properties);return personService;} }7、spring.factories文件
META-INF是自己手動創(chuàng)建的目錄,spring.factories也是手動創(chuàng)建的文件,在該文件中配置自己的自動配置類
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.sf.hello.PersonServiceAutoConfiguration
8、最后將項目打包 mvn clean install??
maven會自動將包復制到你的maven倉庫,在原始項目中pom文件開頭
<groupId>hello</groupId> <artifactId>hello-spring-boot-starter</artifactId> <version>1.0-SNAPSHOT</version>所以你的包在hello文件夾中
9、在其他項目中引入jar包
<dependency><groupId>hello</groupId><artifactId>hello-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version> </dependency>10、在yml文件中編輯配置信息
spring:person:age: 28name: csysex: M11、test類中測試
@SpringBootTest class DemoApplicationTests {@Autowired@SuppressWarnings("ALL")private PersonService personService;@Testvoid contextLoads() {}@Testpublic void testHello(){personService.sayHello();} }到此結束!完美
總結
以上是生活随笔為你收集整理的spring-boot-starter 自定义的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高可用集群下的负载均衡(5):hapro
- 下一篇: CentOS下Oracle11g部署