提高:自定义starter
启动器模块是一个 空 jar 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库;
命名方式:
- 官方命名:
spring-boot-starter-xxx ,比如:spring-boot-starter-web…
- 自定义命名:
xxx-spring-boot-starter ,比如:mybatis-spring-boot-starter
1、在idea中新建个空工程spring-boot-starter-diy
建完以后里面什么都没有
2、新建一个普通Maven模块:zlq-spring-boot-starter
3、新建一个Springboot模块:zlq-spring-boot-starter-autoconfifigure
4、在我们的 启动器模块starter中 导入 autoconfigure 的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>zlq-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies> <!-- 引入自动配置模块 -->
<dependency>
<groupId>com.zlq</groupId>
<artifactId>zlq-spring-boot-starter-autoconfigure</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
5、将 autoconfigure 项目下多余的文件都删掉(测试包也删掉),Pom中只留下一个 spring-boot-starter,这是所有的启动器基本配 置
6、在autoconfigure 模块中编写自己的配置
ConfigurationProperties(prefix = "zlq.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;
}
}
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();
}
}
7、将配置类注入bean
@Configuration
@ConditionalOnWebApplication //使web应用生效
@EnableConfigurationProperties(HelloProperties.class) //使使用 @ConfigurationProperties 注解的类生效
public class HelloServiceConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
public HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
8、在resources编写一个自己的 META-INF\spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zlq.configuration.HelloServiceConfiguration
9、将两个模块打包
10、创建新的SpringBoot项目spring-boot-starter-test,引入web环境
导入我们自己的依赖
<dependency>
<groupId>com.zlq</groupId>
<artifactId>zlq-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
11、编写controller类
@Controller
public class HelloController {
@Autowired
HelloService helloService;
@RequestMapping("/hello")
@ResponseBody
public String sayHello(){
String hello = helloService.sayHello("LiQun");
return hello;
}
}
12、在application.properties中编写配置
zlq.hello.prefix=Hello
zlq.hello.suffix=,you must be HAPPY everyday!
因为我们导入的启动器中的自动配置类HelloProperties中,绑定的前缀是zlq.hello,里面有setPerfix和setSuffix方法