【spring-boot】自定義starter

柘一發表於2018-11-01

一. 命名規範

springboot提供的starter都是以spring-boot-starter-xxx的方式命名的,針對自定義的starter,官方建議以xxx-spring-boot-starter命名予以區分。見官方說明

二. 依賴

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<!-- Import dependency management from Spring Boot -->
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-dependencies</artifactId>
				<version>2.1.0.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
複製程式碼

可以將其他的必要的依賴加入進來。

三. 寫法

1. META-INF

在resources下新建包META-INF,並新增檔案spring.factories。內容如下:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=xxx.HelloStarterEnableAutoConfiguration
複製程式碼

其中xxx為自動配置的核心類。寫法是固定的,springboot會掃描該檔案作為配置類。

2.核心註解

@Configuation

@EnableConfiguationProerties

@ConditionalOnProperties

  1. HelloStarterEnableAutoConfiguration

    @Configuration
    @ConditionalOnClass(HelloService.class)
    @EnableConfigurationProperties(HelloServiceProperties.class)
    public class HelloStarterEnableAutoConfiguration {
    
        private final HelloServiceProperties helloServiceProperties;
    
        @Autowired
        public HelloStarterEnableAutoConfiguration(HelloServiceProperties helloServiceProperties) {
            this.helloServiceProperties = helloServiceProperties;
        }
    
        @Bean
        @ConditionalOnProperty(prefix = "hello.service", name = "enable", havingValue = "true")
        HelloService helloService() {
            return new HelloService(helloServiceProperties.getPrefix(), helloServiceProperties.getSuffix());
        }
    
    }
    複製程式碼
  2. HelloServiceProperties

    @ConfigurationProperties("hello.service")
    public class HelloServiceProperties {
    
        private String prefix;
    
        private String suffix;
    
        public String getPrefix() {
            return prefix;
        }
    
        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }
    
        public String getSuffix() {
            return suffix;
        }
    
        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }
    }
    複製程式碼
    1. HelloService

      public class HelloService {
      
          private String prefix;
      
          private String suffix;
      
          public HelloService(String prefix, String suffix) {
              this.prefix = prefix;
              this.suffix = suffix;
          }
      
          public String say(String text) {
              return String.format("%s , hi , %s , %s", prefix, text, suffix);
          }
      
      }
      複製程式碼

解釋:當專案依賴該starter,並且配置檔案中包含hello.service為字首且hello.service.enable為true時,就會自動生成HelloService的bean。

附上程式碼庫 hello-spring-boot-starter

相關文章