spring boot 自定义starter示例
以下是一个简单的Spring Boot自定义Starter的示例。
- 创建一个新的Maven项目作为Starter:
<groupId>com.example</groupId>
<artifactId>my-custom-spring-boot-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
- 创建一个配置属性类:
package com.example.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "custom.starter")
public class CustomStarterProperties {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- 创建自动配置类:
package com.example.autoconfigure;
import com.example.config.CustomStarterProperties;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(CustomStarterProperties.class)
@EnableAutoConfiguration
public class CustomStarterAutoConfiguration {
private final CustomStarterProperties properties;
public CustomStarterAutoConfiguration(CustomStarterProperties properties) {
this.properties = properties;
}
@Bean
public CustomStarterService customStarterService() {
return new CustomStarterService(properties.getMessage());
}
}
- 创建服务类:
package com.example;
public class CustomStarterService {
private String message;
public CustomStarterService(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
- 在
resources
目录下创建META-INF
文件夹,并在其中创建spring.factories
文件:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.example.autoconfigure.CustomStarterAutoConfiguration
这样一个简单的自定义Spring Boot Starter就完成了。可以将这个项目打包成JAR,并在其他Spring Boot项目中通过Maven或Gradle引用,使用@EnableAutoConfiguration
注解来启用自动配置。
评论已关闭