参考Spring Boot Starters - 御坂研究所
创建自己的starter
starter是依赖的一种synthesize(合成)。
starter会把需要用到的依赖全部包含进来,避免开发者自己手动引入依赖。
starter的逻辑
- pom.xml
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starters</artifactId><version>2.0.4.RELEASE</version></parent><dependencies><!-- 自定义starter依赖此jar包 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies>
- 创建ConfigurationProperties,设置默认配置,如果配置文件有同名的配置,会覆盖默认配置
package org.cc.http.configuration;import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties(prefix="http")// 自动获取配置文件中前缀为http的属性,把值传入对象参数
public class HttpConfigurationProperties {// 如果配置文件中配置了http.url属性,则该默认属性会被覆盖private String url = "http://www.baidu.com/";public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}}
- 创建业务类
package org.cc.http.configuration;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;public class HttpClient {private String url;// 根据url获取网页数据public String getHtml() {try {URL url = new URL(this.url);URLConnection urlConnection = url.openConnection();BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));String line = null;StringBuilder sb = new StringBuilder();while ((line = br.readLine()) != null) {sb.append(line).append("\n");}return sb.toString();} catch (Exception e) {e.printStackTrace();}return "error";}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}}
- starter核心功能:创建HttpAutoConfiguration类,使用HttpConfigurationProperties定义的配置,返回一个业务对象
package org.cc.http.configuration;import javax.annotation.Resource;import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@EnableConfigurationProperties(HttpConfigurationProperties.class)
public class HttpAutoConfiguration {@Resourceprivate HttpConfigurationProperties properties; // 使用配置// 在Spring上下文中创建一个对象@Bean@ConditionalOnMissingBeanpublic HttpClient init() {HttpClient client = new HttpClient();String url = properties.getUrl();client.setUrl(url);return client;}}
- 将HttpAutoConfiguration加入到src\main\resources\META-INF\spring.factories进行声明
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.cc.http.configuration.HttpAutoConfiguration
创建好starter之后,打包就可以使用了。
springboot配置详解
Spring Boot 2.0 教程 - 配置详解 - NNS - 博客园Spring Boot 可以通过properties文件,YAML文件,环境变量和命令行参数进行配置。属性值可以通过,@Value注解,Environment或者ConfigurationProperhttps://www.cnblogs.com/hitandrew/p/9062861.html
Java启动参数和脚本 - Howlet - 博客园