springboot 学习(三) 自定义starter启动器
当我们创建springboot,并在创建选中依赖,比如web,就可以在pom.xml中看到,一些启动器,我们如何自定义这些启动器呢
说明
启动器模块是一个 空 jar 文件,仅提供辅助性依赖管理,这些依赖可能用于自动装配或者其他类库;
命名归约:
官方命名:
-
前缀:spring-boot-starter-xxx
-
比如:spring-boot-starter-web....
自定义命名:
-
xxx-spring-boot-starter
-
比如:mybatis-spring-boot-starter
编写启动器
首先创建一个springboot项目,不用勾选其他要导入的依赖
创建后清理掉test目录,自带的主启动类,并且在pom.xml中的依赖保留spring-boot-starter,这是启动器的基础依赖,如下:
注意hys和resources目录文件要为空,这个图下的是启动器自制好后的文件
首先编写一个hello服务:helloService
参数为helloProperties类的引用
package com.hys;
public class helloService {
private helloProperties helloProperties;
public com.hys.helloProperties getHelloProperties() {
return helloProperties;
}
public void setHelloProperties(com.hys.helloProperties helloProperties) {
this.helloProperties = helloProperties;
}
public String sayHello(){
return "hello:"+helloProperties.getName()+helloProperties.getAge();
}
}
helloProperties类的编写,需要使用@ConfigurationProperties,表示获取配置文件里的值,注意前缀prefix = "com.hys"
package com.hys;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "com.hys")
public class helloProperties {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
配置类的编写:helloAutoConfiguration
@Configuration 配置类声明
@EnableConfigurationProperties(helloProperties.class) 让@ConfigurationProperties这个注解生效,并向容器中导入组件。
@bean 注册helloService
package com.hys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(helloProperties.class)
public class helloAutoConfiguration {
@Autowired
helloProperties helloProperties;
@Bean
public helloService helloService(){
helloService helloService =new helloService();
helloService.setHelloProperties(helloProperties);
return helloService;
}
}
在resources/META-INF/spring.factories文件中写入以下值
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.hys.helloAutoConfiguration
生成对应jar包并导入到仓库中
测试:
创建springboot项目,并导入刚自定义的依赖
在配置文件编写helloProperties类的属性,如下
测试代码及结果:
@SpringBootTest
class Springboot06DivstarterApplicationTests {
@Autowired
helloService helloService;
@Test
void contextLoads() {
System.out.println(helloService.sayHello());
}
}