一、创建自定义starter
先创建一个my-starter的module,主要配置依赖如下
<artifactId>my-starter</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
建一个自动读取配置的类
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
在application.yml中配置hello.msg就能读取到
弄个自动配置的bean
public class HelloService {
private String msg;
public String sayHello() {
return "Hello " + msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
弄个自动配置的配置类,主要自动装载上面的HelloService类
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello", value = "enable", matchIfMissing = true)
public class HelloAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
//当容器中没有HelloService就自动注入一个bean
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setMsg(helloServiceProperties.getMsg());
return helloService;
}
}
还有一个重要步骤:在resources文件夹下建一个META-INF文件夹,再建一个spring.factories文件,写上
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.season.HelloAutoConfiguration
最后利用maven进行clean、install
二、测试starter
创建另一个my-starter-test的module,主要配置依赖如下
<artifactId>my-starter-test</artifactId>
<dependencies>
<dependency>
<groupId>com.season</groupId>
<artifactId>my-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
然后再application.yml中写上
hello:
msg: season
启动类如下:
@RestController
@SpringBootApplication
public class HelloSpringBootStarterTestApplication {
@Autowired
private HelloService helloService;
@RequestMapping("/")
public String index() {
return helloService.sayHello();
}
public static void main(String[] args) {
SpringApplication.run(HelloSpringBootStarterTestApplication.class, args);
}
}
启动,然后访问本地8080端口就能看到输出”hello season“了。