SpringBoot提供了许多启动器模块来快速启动和运行。 SpringBoot的自动配置机制负责根据各种标准代表我们配置SpringBean。

除了Core Spring Team提供的现成的springboot启动器之外,我们还可以创建自己的启动器模块。

在本文中,我们将研究如何创建自定义的SpringBoot启动器。 为了演示它,我们将创建twitter4j-spring-boot-starter ,它将自动配置Twitter4J bean。

为此,我们将创建:

  1. twitter4j-spring-boot-autoconfigure模块,其中包含Twitter4J AutoConfiguration bean定义
  2. twitter4j-spring-boot-starter模块,用于获取twitter4j-spring-boot-autoconfiguretwitter4j-core依赖项
  3. 使用twitter4j-spring-boot-starter的示例应用程序

创建父模块spring-boot-starter-twitter4j

首先,我们将创建一个父pom类型模块,以定义依赖项版本和子模块。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sivalabs</groupId><artifactId>spring-boot-starter-twitter4j</artifactId><packaging>pom</packaging><version>1.0-SNAPSHOT</version><name>spring-boot-starter-twitter4j</name><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><twitter4j.version>4.0.3</twitter4j.version><spring-boot.version>1.3.2.RELEASE</spring-boot.version></properties><modules><module>twitter4j-spring-boot-autoconfigure</module><module>twitter4j-spring-boot-starter</module><module>twitter4j-spring-boot-sample</module></modules><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>org.twitter4j</groupId><artifactId>twitter4j-core</artifactId><version>${twitter4j.version}</version></dependency></dependencies></dependencyManagement></project>

在此pom.xml中,我们在部分中定义了SpringBoot和Twitter4j版本,因此我们无需在所有地方指定版本。

创建twitter4j-spring-boot-autoconfigure模块

在我们的父Maven模块spring-boot-starter-twitter4j中创建一个名为twitter4j-spring-boot-autoconfigure的子模块。

添加Maven依赖项,例如spring-boot, spring-boot-autoconfiguretwitter4j-corejunit ,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sivalabs</groupId><artifactId>twitter4j-spring-boot-autoconfigure</artifactId><packaging>jar</packaging><version>1.0-SNAPSHOT</version><parent><groupId>com.sivalabs</groupId><artifactId>spring-boot-starter-twitter4j</artifactId><version>1.0-SNAPSHOT</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot</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><optional>true</optional></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.twitter4j</groupId><artifactId>twitter4j-core</artifactId><optional>true</optional></dependency></dependencies>
</project>

请注意,我们已将twitter4j-core指定为可选依赖项,因为仅当将twitter4j-spring-boot-starter添加到项目时,才应将twitter4j-core添加到项目中。

创建Twitter4jProperties来保存Twitter4J配置参数

创建Twitter4jProperties.java来保存Twitter4J OAuth配置参数。

package com.sivalabs.spring.boot.autoconfigure;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;@ConfigurationProperties(prefix= Twitter4jProperties.TWITTER4J_PREFIX)
public class Twitter4jProperties {public static final String TWITTER4J_PREFIX = "twitter4j";private Boolean debug = false;@NestedConfigurationPropertyprivate OAuth oauth = new OAuth();public Boolean getDebug() {return debug;}public void setDebug(Boolean debug) {this.debug = debug;}public OAuth getOauth() {return oauth;}public void setOauth(OAuth oauth) {this.oauth = oauth;}public static class OAuth {private String consumerKey;private String consumerSecret;private String accessToken;private String accessTokenSecret;public String getConsumerKey() {return consumerKey;}public void setConsumerKey(String consumerKey) {this.consumerKey = consumerKey;}public String getConsumerSecret() {return consumerSecret;}public void setConsumerSecret(String consumerSecret) {this.consumerSecret = consumerSecret;}public String getAccessToken() {return accessToken;}public void setAccessToken(String accessToken) {this.accessToken = accessToken;}public String getAccessTokenSecret() {return accessTokenSecret;}public void setAccessTokenSecret(String accessTokenSecret) {this.accessTokenSecret = accessTokenSecret;}}
}

使用此配置对象,我们可以在application.properties中配置twitter4j属性,如下所示:

twitter4j.debug=true
twitter4j.oauth.consumer-key=your-consumer-key-here
twitter4j.oauth.consumer-secret=your-consumer-secret-here
twitter4j.oauth.access-token=your-access-token-here
twitter4j.oauth.access-token-secret=your-access-token-secret-here

创建Twitter4jAutoConfiguration来自动配置Twitter4J

这是我们启动程序的关键部分。

Twitter4jAutoConfiguration配置类包含将根据某些条件自动配置的Bean定义。

那是什么标准?

  • 如果twitter4j.TwitterFactory .class在类路径上
  • 如果尚未明确定义TwitterFactory bean

因此, Twitter4jAutoConfiguration像这样。

package com.sivalabs.spring.boot.autoconfigure;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
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;import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;@Configuration
@ConditionalOnClass({ TwitterFactory.class, Twitter.class })
@EnableConfigurationProperties(Twitter4jProperties.class)
public class Twitter4jAutoConfiguration {private static Log log = LogFactory.getLog(Twitter4jAutoConfiguration.class);@Autowiredprivate Twitter4jProperties properties;@Bean@ConditionalOnMissingBeanpublic TwitterFactory twitterFactory(){if (this.properties.getOauth().getConsumerKey() == null|| this.properties.getOauth().getConsumerSecret() == null|| this.properties.getOauth().getAccessToken() == null|| this.properties.getOauth().getAccessTokenSecret() == null){String msg = "Twitter4j properties not configured properly." + " Please check twitter4j.* properties settings in configuration file.";log.error(msg);throw new RuntimeException(msg);}ConfigurationBuilder cb = new ConfigurationBuilder();cb.setDebugEnabled(properties.getDebug()).setOAuthConsumerKey(properties.getOauth().getConsumerKey()).setOAuthConsumerSecret(properties.getOauth().getConsumerSecret()).setOAuthAccessToken(properties.getOauth().getAccessToken()).setOAuthAccessTokenSecret(properties.getOauth().getAccessTokenSecret());TwitterFactory tf = new TwitterFactory(cb.build());return tf;}@Bean@ConditionalOnMissingBeanpublic Twitter twitter(TwitterFactory twitterFactory){return twitterFactory.getInstance();}}

我们使用@ConditionalOnClass({TwitterFactory.class,Twitter.class})来指定仅当存在TwitterFactory.class,Twitter.class类时才进行此自动配置。

我们还对bean定义方法使用了@ConditionalOnMissingBean来指定仅当尚未明确定义TwitterFactory / Twitter bean时才考虑此bean定义。

还要注意,我们已经使用@EnableConfigurationProperties(Twitter4jProperties.class)进行了注释,以启用对ConfigurationProperties的支持并注入了Twitter4jProperties bean。

现在,我们需要在src / main / resources / META-INF / spring.factories文件中配置自定义Twitter4jAutoConfiguration ,如下所示:

org.springframework.boot.autoconfigure.EnableAutoConfiguration =
com.sivalabs.spring.boot.autoconfigure.Twitter4jAutoConfiguration

创建twitter4j-spring-boot-starter模块

在我们的父Maven模块spring-boot-starter-twitter4j中创建一个名为twitter4j-spring-boot-starter的子模块。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sivalabs</groupId><artifactId>twitter4j-spring-boot-starter</artifactId><packaging>jar</packaging><version>1.0-SNAPSHOT</version><parent><groupId>com.sivalabs</groupId><artifactId>spring-boot-starter-twitter4j</artifactId><version>1.0-SNAPSHOT</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>com.sivalabs</groupId><artifactId>twitter4j-spring-boot-autoconfigure</artifactId><version>${project.version}</version></dependency><dependency><groupId>org.twitter4j</groupId><artifactId>twitter4j-core</artifactId></dependency></dependencies></project>

请注意,在这个Maven模块中,我们实际上是引入twitter4j-core依赖关系。

我们不需要在此模块中添加任何代码,但是可以选择在src / main / resources / META-INF / spring.provides文件中指定通过此启动程序提供的依赖 ,如下所示:

提供:twitter4j-core

这就是我们的入门者。

让我们使用全新的启动程序twitter4j-spring-boot-starter创建示例。

创建twitter4j-spring-boot-sample示例应用程序

让我们创建一个简单的SpringBoot应用程序,并添加我们的twitter4j-spring-boot-starter依赖项。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.sivalabs</groupId><artifactId>twitter4j-spring-boot-sample</artifactId><packaging>jar</packaging><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.3.2.RELEASE</version></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><java.version>1.8</java.version></properties><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build><dependencies><dependency><groupId>com.sivalabs</groupId><artifactId>twitter4j-spring-boot-starter</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies></project>

创建入口点类SpringbootTwitter4jDemoApplication ,如下所示:

package com.sivalabs.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringbootTwitter4jDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootTwitter4jDemoApplication.class, args);}
}

创建TweetService ,如下所示:

package com.sivalabs.demo;import java.util.ArrayList;
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;@Service
public class TweetService {@Autowiredprivate Twitter twitter;public List<String> getLatestTweets(){List<String> tweets = new ArrayList<>();try {ResponseList<Status> homeTimeline = twitter.getHomeTimeline();for (Status status : homeTimeline) {tweets.add(status.getText());}} catch (TwitterException e) {throw new RuntimeException(e);}return tweets;}
}

现在创建一个测试以验证我们的Twitter4j AutoConfigutation。

在此之前,请确保已将twitter4j oauth配置参数设置为实际值。 您可以从https://apps.twitter.com/获得它们

package com.sivalabs.demo;import java.util.List;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import twitter4j.TwitterException;@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringbootTwitter4jDemoApplication.class)
public class SpringbootTwitter4jDemoApplicationTest  {@Autowiredprivate TweetService tweetService;@Testpublic void testGetTweets() throws TwitterException {List<String> tweets = tweetService.getLatestTweets();for (String tweet : tweets) {System.err.println(tweet);}}}

现在,您应该能够在控制台输出中看到最新的推文。

  • 您可以在GitHub上找到代码: https//github.com/sivaprasadreddy/twitter4j-spring-boot-starter

翻译自: https://www.javacodegeeks.com/2016/02/creating-custom-springboot-starter-twitter4j.html

为Twitter4j创建自定义SpringBoot Starter相关推荐

  1. twitter自定义api_为Twitter4j创建自定义SpringBoot Starter

    twitter自定义api SpringBoot提供了许多启动器模块来快速启动和运行. SpringBoot的自动配置机制负责根据各种标准代表我们配置SpringBean. 除了Core Spring ...

  2. SpringSecurity Oauth2 - 自定义 SpringBoot Starter 远程访问受限资源

    文章目录 1. 自定义 SpringBoot Starter 1. 统一的dependency管理 2. 对外暴露 properties 3. 实现自动装配 4. 指定自动配置类的路径 META-IN ...

  3. 自定义SpringBoot Starter实现

    文章目录 自定义stater pom文件 配置文件类properties 使用配置类 创建AutoConfiguration 项目结构 自定义stater pom文件 引入自动配置类spring-bo ...

  4. 简述SpringBoot Starter原理及自定义实现

    简述SpringBoot Starter原理及自定义实现 一.简述 二.结合SpringBoot启动原理看容器如何实现自动装配 三.解析mybatis-spring-boot-starter包看myb ...

  5. 自定义一个SpringBoot Starter

    文章目录 简介 使用Spring Initializr创建一个项目 定义一个配置信息映射类 定义一个Service 定义一个配置类自动装配Service 在spring.factories中指定自动装 ...

  6. 深入理解springboot starter

    定义:Spring Boot Starter 是在 SpringBoot 组件中被提出来的一种概念,官网概念 Starter POMs are a set of convenient dependen ...

  7. 如何自定义一个starter组件

    本文来说下如何自定义一个stater组件. 文章目录 概述 原理浅谈 术语介绍 starter组件命名规则 概述 我们都知道可以使用 SpringBoot 快速的开发基于 Spring 框架的项目.由 ...

  8. Spring Boot学习总结(22)——如何定制自己的 springboot starter 组件呢?

    引言 我们日常项目中都会用到springboot,只要我们用到springboot,一定会用到各种spring-boot-starter.下面我们通过一个springboot starter 的dem ...

  9. 如何创建自定义maven archetype?

    如何创建自定义maven archetype? 文章目录 如何创建自定义maven archetype? 1. 什么是archetype 2. 创建项目模板 3. 创建archetype目录结构 4. ...

最新文章

  1. 从零开始MDT2010学习手记(二) 创建共享工作目录
  2. vs2010配置python_VS2010下python3的配置
  3. linux 终端 tty 简介
  4. Python基础(3) - 数据类型:2字符串类型
  5. nginx+keepalived双机热备
  6. java计数器策略模式_java设计模式(二十一)--策略模式
  7. CCF业务总部和学术交流中心落户苏州相城
  8. jmeter压力性能测试-多台机器并发请求
  9. VirtualBox Failed to open/create the internal network 错误处理
  10. W-3 用grub4dos安装Windows7、Ubuntu 12.10双系统(图解)
  11. C++ 10 进制 转 16进制
  12. 饱受诟病的白板面试,为什么沿用至今?
  13. vue 兼容IE解决方案, Babel .babelrc
  14. MoveIt! RViz Visual Tools设置
  15. 群辉nas虚拟linux,UNRAID教程:3分钟 用unraid自带的虚拟机 安装 黑群晖NAS DSM系统 很强大!...
  16. 行业资讯 | 深圳:BIM法定化,开历史之先河
  17. 华为存储OceanStor 5110V5 CA证书即将过期告警处理
  18. opencv人脸检测输出的置信率
  19. 2020年全省彩礼排名_2020国人彩礼地图:哪个省的彩礼最贵?
  20. 【CS 1376】帕秋莉•诺蕾姬(Hash)

热门文章

  1. 1分钟了解基于内容的推荐,pm又懂了
  2. Redis入门(一)之安装
  3. Java的系统Property
  4. 你们好好的学,回头教教我~
  5. ssh(Spring+Spring mvc+hibernate)——Dept.hbm.xml
  6. 在gitee上创建自己的仓库步骤
  7. Android软键盘弹出时,覆盖布局,不是把布局顶上去的解决方法
  8. android之视频直播与播放Vitamio
  9. php中对象的遍历输出,PHP中的对象遍历技巧
  10. 中南大学计算机网.doc,中南大学计算机网络实验报告.doc