SpringBoot-自定义Starter精华版
// 自定义Spring Boot Starter的核心组件示例
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
// 配置属性类
@ConfigurationProperties(prefix = "sample")
public class SampleProperties {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
// 配置属性绑定和自动配置的配置类
@Configuration
@EnableConfigurationProperties(SampleProperties.class)
public class SampleConfiguration {
private final SampleProperties properties;
public SampleConfiguration(SampleProperties properties) {
this.properties = properties;
}
@Bean
public WebMvcConfigurer helloController() {
return new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("hello");
}
};
}
@Bean
public HelloService helloService() {
return new HelloService(properties.getMessage());
}
}
// 服务类
public class HelloService {
private String message;
public HelloService(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
这个示例展示了如何创建一个自定义Spring Boot Starter的核心组件。SampleProperties
类用于绑定配置文件中的属性。SampleConfiguration
类使用@EnableConfigurationProperties
注解来启用属性绑定,并且提供了一个WebMvcConfigurer
和一个HelloService
的Bean,以展示如何添加额外的配置和服务。HelloService
类用于处理具体的业务逻辑。这个示例精简了代码,教给开发者如何编写自定义Starter的核心部分。
评论已关闭