1.建立一个空白项目:shu-spring-boot-starter
项目结构:
2.pom.xml中只剩
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
3.编写HelloProperties 配置类:
package com.shusl;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "hello") // 对外提供的前缀,相当于其它引入当前starter在properties文件使用hello.属性即可对下面属性进行赋值
public class HelloProperties {
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;
}
}
4.我们编写一个自己的服务:
package com.shusl;
public class HelloService {
HelloProperties helloProperties;
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHello(String name){
return helloProperties.getPrefix() +" "+name +" "+helloProperties.getSuffix();
}
}
5.编写HelloProperties 配置类
package com.shusl;
@Configuration
@ConditionalOnWebApplication // 条件配置类,该注解表示在web环境下才生效,相关的其它条件可以使用@ConditionXXX
@EnableConfigurationProperties(HelloProperties.class) // 表示HelloProperties作为配置类使用
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties; // 作为配置类目的就是想在sayHello方法返会的字符串加上前缀和后缀
@Bean
public HelloService helloService() { // 将HelloService注入到IOC容器
HelloService service = new HelloService();
service.setHelloProperties(helloProperties);
return service;
}
}
6.配置文件配置自已写的服务
在resources编写一个自己的 META-INF\spring.factories
xxx-spring-boot-starter = HelloProperties 配置类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.shusl.HelloServiceAutoConfiguration
7.点击安装到maven仓库中
成功之后新建一个springBoot项目:shu-spring-boot-starter-autoconfigure测试
项目结构:
1.pom.xml导入自已配置的依赖
第一个项目的这个就是Hello依赖
shu-spring-boot-starter-autoconfigure添加:
<!-- 引入自动配置模块 -->
<dependency>
<groupId>com.shusl</groupId>
<artifactId>shu-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
2.编写一个 HelloController 测试
package com.shusl.controller;
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@RequestMapping("/hello")
public String hello(){
return helloService.sayHello("shu");
}
}
3.编写配置文件 application.properties对应配置文件的HelloProperties
hello.prefix=HUASHENGSHU
hello.suffix=Hello World
4.启动测试