学习点
- 编写自动的配置启动项
- jar供给第三方maven依赖
步骤
- 一、建立一个空项目
- 二、创建需要给第三方引用的启动项,创建需要给地方的内容
- 三、先创建maven项目,供给第三方引用
- 四、名字规范:作用-上面的项目名字
- 五、common-reference-startup 引入 explain-common-reference-startup
<dependencies> <dependency> <groupId>com.xk</groupId> <artifactId>explain-common-reference-startup</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies>
- 六、删除xplain-common-reference-startup无用的:
删除pom:插件、test
删除test类、配置文件、 - 七、写一个自动配置属性类
@ConfigurationProperties(prefix = "com.xiaoke") 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(); } }
- 九、编写配置类,让引用类生效(加到容器中)
@Configuration @ConditionalOnWebApplication//web应用才生效 @EnableConfigurationProperties(HelloProperties.class) //让配置的属性起作用,下面就可以引用 public class HelloServiceAutoConfiguration { @Autowired HelloProperties helloProperties; @Bean public HelloService helloService(){ HelloService helloService = new HelloService(); helloService.setHelloProperties(helloProperties); return helloService; } }
- 十、让自己写的配置类生效、创建spring.factories
#使我们的HelloServiceAutoConfiguration自动配置类生效 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.xk.explaincommonreferencestartup.HelloServiceAutoConfiguration
-
十一、打包Lifecycle --> install,先次项目,在主项目
-
十二、测试
<dependency> <groupId>com.xk</groupId> <artifactId>common-reference-startup</artifactId> <version>1.0-SNAPSHOT</version> </dependency>