自定义springboot-starter
一、 编写starter
二、编写测试类
------------------------------------------------------------
新建springboot项目,删掉测试文件,pom里,只保留3个(自动配置,自动配置处理用来在yml提示),去掉build章节
<dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starterartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-autoconfigureartifactId> dependency> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-configuration-processorartifactId> dependency> dependencies>
编写HelloProperties,前缀用大小写易出异常。注意大小写。
@ConfigurationProperties(prefix = "hello") public class HelloProperties { private String name = "anon"; private String address = "unname address"; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "HelloProperties{" + "name='" + name + '\'' + ", address='" + address + '\'' + '}'; } }
编写自动配置类HelloServiceAutoConfiguration,
注解导入上一个配置文件,注意构造器注入属性
@Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { private HelloProperties helloProperties; public HelloServiceAutoConfiguration(HelloProperties helloProperties) { this.helloProperties = helloProperties; } @Bean @ConditionalOnMissingBean public HelloService helloService(){ return new HelloService(helloProperties.getName(),helloProperties.getAddress()); } }
编写业务方法HelloService,注意构造器
public class HelloService { private String name; private String address; public HelloService(String name, String address) { this.name = name; this.address = address; } public String sayHello(){ return "你好,我i是"+name+",来自"+address; } }
在resources里,建立META-INF/spring.factories 文件,让springboot自动扫描启动类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.taotao.config.HelloServiceAutoConfiguration
然后maven install到本地仓库,安装完毕后,进idea,更新一下本地仓库,不必更新远程仓库。否则再下一步中,不识别新安装的starter
---------------------------------------------------------
建立测试文件 ,新建工程demo
在pom中引入刚才的starter坐标。
<dependency> <groupId>cn.taotaogroupId> <artifactId>demoStartartifactId> <version>0.0.1-SNAPSHOTversion> dependency>
新建测试类
@Autowired private HelloService helloService; @Test void hello(){ System.out.println("helloService.sayHello() = " + helloService.sayHello()); }
可以在application.yml 中测试注入的值