如何自定义一个 SpringBoot 的 starter 包

starter 包与自动配置的概念

  • 我们知道 SpringBoot 通过 starter 包引入对应的第三方 jar 包,然后通过自动配置机制来自动创建该第三方 jar 包对应的功能的 bean 对象。如通过引入 spring-boot-starter-data-redis 这个 starter 包并且在 application.properties 属性配置文件配置 Redis 服务器的域名和端口号,则可以直接注入 RedisTemplate 对应的 bean 对象来使用。步骤如下:
  1. 引入 spring-boot-starter-data-redis 这个 starter 包:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  2. 在 application.properties 配置文件添加 Redis 服务器的配置:

    # redis 配置
    spring.redis.host=localhost
    spring.redis.port=6379
    
  3. 直接在应用代码注入 RedisTemplate 类的 bean 对象,此时可以通过 bean 对象直接进行数据存取操作:

    @Service
    public class TestService {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        public String getRedisStrValue(String key) {
            return (String)redisTemplate.opsForValue().get(key);
        }
    
    
    }
    
  • 所以通过 SpringBoot 的 starter 包和自动配置机制,使用第三方功能就是这么简单。那么我们是否可以自定义一个 starter 包,这样就可以直接在项目中按照这种方式使用对应的功能?答案是可以的。

自定义 starter 包

  • 我们在这里以开发一个天气查询的 starter 包为例来介绍 starter 包的自定义。
  • 基本思路是在该 starter 包提供一个 WeatherTemplate 模板类并提供一个根据地区代号查询该地区天气情况的方法,其中查询天气是使用国家气象局的API,即在该 starter 包内部默认使用一个国家气象局的天气查询 API ,然后用户可以在 application.properties 配置国家气象局的其他天气查询 API。
  1. 定义业务服务类 WeatherTemplate 实现,该业务服务类是一个普通的 Java 类。

    public class WeatherTemplate {
    
        /**
         * 国家气象局天气查询接口
         */
        private static String DEFAULT_QUERY_API = "http://www.weather.com.cn/data/cityinfo/";
        private static String WEATHER_QUERY_API_TYPE = ".html";
    
        private String queryUrl;
    
        public WeatherTemplate() {
            this.queryUrl = DEFAULT_QUERY_API;
        }
    
        public WeatherTemplate(String url) {
            this.queryUrl = url;
        }
    
        /**
         * 根据给定的地区代号,查询天气情况
         * 代号查询:https://www.cnblogs.com/wangjingblogs/p/3192953.html
         * @param areaCode
         * @return
         */
        public String query(String areaCode) {
            String url = queryUrl + areaCode + WEATHER_QUERY_API_TYPE;
            RestTemplate restTemplate=new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> entity = new HttpEntity<String>(headers);
            String strbody=restTemplate.exchange(url, HttpMethod.GET, entity,String.class).getBody();
            try {
                // 解决中文乱码问题
                return new String(strbody.getBytes("ISO-8859-1"),"UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
  2. 定义属性类 WeatherProperties,该类解析 application.properties 文件内以 weather.query 开头的属性。

    @ConfigurationProperties(prefix = "weather.query")
    public class WeatherProperties {
        private String url;
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    }
    

    例如,可以在使用时进行如下配置,替换默认的查询url:http://www.weather.com.cn/data/cityinfo/

    weather.query.url=http://www.weather.com.cn/data/sk/
    
  3. 定义使用了 @Configuration 注解的配置类实现,其中使用 @ConditionalOnClass 条件注解来判断类路径是否存在 WeatherTemplate 类,并且在内部的 weatherTempalte 方法中创建该对象。

    @Configuration
    @ConditionalOnClass(WeatherTemplate.class)
    // 引入属性配置类 WeatherProperties
    @EnableConfigurationProperties(WeatherProperties.class)
    public class WeatherAutoConfiguration {
    
        @Autowired
        private WeatherProperties weatherProperties;
    
        @Bean
        @ConditionalOnMissingBean
        public WeatherTemplate weatherTemplate() {
            // 如果用户配置了其他API,则使用用户配置的,否则使用默认的。
            WeatherTemplate weatherTemplate = weatherProperties.getUrl()==null ? new WeatherTemplate() :
                    new WeatherTemplate(weatherProperties.getUrl());
            return weatherTemplate;
        }
    }
    
  4. 在 resources 目录新增 META-INF 目录,并且新建 spring.factories 文件,文件内容为以上定义的配置类,以便被 SpringBoot 的自动配置机制识别。

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      com.yzxie.study.java.demo.weatherstarter.WeatherAutoConfiguration
    
  5. 编译打包,之后可以直接在其他项目引入,并且通过 @Autowired 注解注入 WeatherTemplate,大功告成。
    编译命令:

     mvn clean install -Dmaven.test.skip=true
    

    引入使用:

    @Autowired
    private WeatherTemplate weatherTemplate;
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值