自定义Starter(重要!!!)
自定义Starter
项目–>自定义Starter–>自定义Starter-autoconfigurer
1. 创建自定义Starter-autoconfigurer项目(自动配置模块)
pom.xml
:引入spring-boot-starter
所有starter
的基本配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
2. 在Starter-autoconfigurer项目下创建HelloProperties
自定义属性配置
(1)@ConfigurationProperties(prefix = "lemon.hello")
:指定属性配置前缀为lemon.hello
,用于绑定配置文件中以lemon.hello
开头的配置
(2)需要添加get,set方法才能进行使用
HelloProperties
:
@ConfigurationProperties(prefix = "lemon.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;
}
}
3. 在Starter-autoconfigurer项目下创建HelloService
,用于编写实际方法
HelloService
:
public class HelloService {
HelloProperties helloProperties;
public String sayHello(String name){
return helloProperties.getPrefix() + "-" + name + helloProperties.getSuffix();
}
public HelloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(HelloProperties helloProperties) {
this.helloProperties = helloProperties;
}
}
4. 在Starter-autoconfigurer项目下创建HelloServiceAutoConfiguration
自动配置类,给容器中添加HelloService
组件
(1)@Configuration
:标注这是一个配置类
(2)@ConditionalOnWebApplication
:只有在Web应用下才生效
(3)@EnableConfigurationProperties(HelloProperties.class)
:让HelloProperties
配置生效
HelloServiceAutoConfiguration
:
@Configuration
@ConditionalOnWebApplication // Web应用才生效
@EnableConfigurationProperties(HelloProperties.class) // 让HelloProperties配置生效
public class HelloServiceAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService service = new HelloService();
service.setHelloProperties(helloProperties);
return service;
}
}
5. 在Starter-autoconfigurer项目下配置加载自己创建的自动配置类
application.yml
:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.lemon.starter.HelloServiceAutoConfiguration
6. 创建自定义Starter(启动器模块)
只需要引入自定义的自动配置模块自定义Starter-autoconfigurer
pom.xml
:
<dependency>
<groupId>com.lemon.starter</groupId>
<artifactId>lemon-spring-boot-starter-autoconfigurer</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
7. 使用Maven对这两个自定义模块进行install
8. 测试
(1)pom.xml
:只需要引入自定义Starter启动器即可
<dependency>
<groupId>com.lemon.starter</groupId>
<artifactId>lemon-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
(2)创建HelloController
类进行测试,自动注入HelloService
即可调用sayHello
方法
HelloController
:
@RestController
public class HelloController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String hello(){
return helloService.sayHello("haha");
}
}
(3)在全局配置文件中配置HelloService
的属性(前后缀)
application.properties
:
lemon.hello.prefix=Lemon
lemon.hello.suffix=HELLO WORLD
效果:
访问http://localhost:8080/hello
,显示Lemon-hahaHELLO WORLD