javascript
Spring Boot自定义Start组件开发
Start 組件開發,核心是自動注解類的注解順序,即根據條件進行注解。
首先我們來理解@Configuration、@Value、@Bean注解
以DataSourceAutoConfiguration類注解為例,
@Configuration表名此類是個配置類;
@ConditionalOnClass表明當DataSource.class, EmbeddedDatabaseType.class存在時才會繼續進行下面的配置;@EnableConfigurationProperties從IOC容器中獲取application.properties配置文件的Bean;
@Import 導入相關類。
@ConfigurationProperties注解主要用來把properties配置文件轉化為bean來使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。如果只配置@ConfigurationProperties注解,在IOC容器中是獲取不到properties配置文件轉化的bean的。
@EnableConfigurationProperties詳細說明
自動加載核心注解說明
有了以上的了解后,來創建 Maven 項目, 目錄結構如下:
添加pom.xml依賴(根據組件功能添加)
在使用Spring官方的Starter時通常可以在application.properties中來配置參數覆蓋掉默認的值。即sex的值會被配置文件中的值替換掉。
PersonProperties 類
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());} }PersonServiceAutoConfiguration 類
@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;} }spring.factories文件
注意:META-INF是自己手動創建的目錄,spring.factories也是手動創建的文件,在該文件中配置自己的自動配置類
最后將項目打包 mvn clean install
在另一個項目中添加依賴 如何在項目中添加本地jar包
<dependency><groupId>cnbi</groupId><artifactId>helloworld-spring-boot-starter</artifactId><version>1.0</version></dependency>配置application.properties
spring.person.age=23 spring.person.name=ss spring.person.sex=F啟動測試類
@RunWith(SpringRunner.class) @SpringBootTest public class LarkApplicationTests {@Autowired@SuppressWarnings("ALL")private PersonService personService;@Testpublic void testHelloWorld() {personService.sayHello();}}2019-09-11 09:25:19.453 INFO 7272 — [ main] com.tiamo.lark.LarkApplicationTests : Started LarkApplicationTests in 4.893 seconds (JVM running for 6.7)
大家好,我叫: ss, 今年23歲, 性別: F
總結
以上是生活随笔為你收集整理的Spring Boot自定义Start组件开发的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将字符串中大写转换成小写,小写转换成大写
- 下一篇: javascript检查移动设备是否支持