自定义springboot-starter
一、 编写starter
二、编写测试类
------------------------------------------------------------
新建springboot项目,删掉测试文件,pom里,只保留3个(自动配置,自动配置处理用来在yml提示),去掉build章节
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </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.taotao</groupId> <artifactId>demoStart</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
新建测试类
@Autowired private HelloService helloService; @Test void hello(){ System.out.println("helloService.sayHello() = " + helloService.sayHello()); }
可以在application.yml 中测试注入的值
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2020-05-08 微信开发中,本地缓存,不同步的问题