为Twitter4j创建自定义SpringBoot Starter

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/354087.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mac php gd库,mac下安装GD库FreeType

MacBook Pro安装的新系统10.10.3&#xff0c;PHP环境也是默认就有的&#xff0c;GD库在默认情况下也安装过了&#xff0c;但在使用验证码的时候&#xff0c;提示GD库不支持FreeType&#xff0c;这里我们手动安装一下。法一&#xff1a;安装 FreeType前往苹果官方开源支持&#…

php异步查询数据库,php中mysql数据库异步查询实现

问题通常一个web应用的性能瓶颈在数据库。因为&#xff0c;通常情况下php中mysql查询是串行的。也就是说&#xff0c;如果指定两条sql语句时&#xff0c;第二条sql语句会等到第一条sql语句执行完毕再去执行。这个时候&#xff0c;如果执行2条sql语句&#xff0c;每条执行时间为…

java btrace_BTrace:Java开发人员工具箱中的隐藏宝石

java btrace这篇文章是关于BTrace的 &#xff0c;我正在考虑将其作为Java开发人员的隐藏宝藏。 BTrace是用于Java平台的安全&#xff0c;动态跟踪工具。 BTrace可用于动态跟踪正在运行的Java程序&#xff08;类似于DTrace&#xff0c;适用于OpenSolaris应用程序和OS&#xff09…

共享文件夹不能访问的问题解决

打开控制面板--管理工具--服务--webclinet&#xff0c;设为自动&#xff0c;启动。重启电脑&#xff0c;搞定&#xff01;转载于:https://www.cnblogs.com/atlj/p/8481257.html

xampp浏览php出现乱码,dvwa+xampp搭建显示乱码的问题及解决方案

如图&#xff0c;dvwa显示乱码&#xff0c;解决办法有两个&#xff1a;1、方法一是&#xff0c;临时解决办法&#xff0c;也就是每次都得手动修改&#xff1a;利用浏览器的编码修改2、方法二是&#xff1a;永久方案&#xff0c;那就是修改dvwa的配置文件&#xff0c;修改默认编…

HotSpot的-XshowSettings标志的简单性和价值

一个方便的HotSpot JVM标志 &#xff08; 选项为Java启动 java &#xff09;是-XshowSettings选项。 Oracle Java启动器描述页面中对此选项进行了如下描述 &#xff1a; -XshowSettings &#xff1a; category显示设置并继续。 该选项的可能类别参数包括&#xff1a; all显示所…

Python验证码简单实现(数字和大写字母组成的4位验证码)

#数字和英文大写字母的4位随机数 def checkcode(): #def 定义方法 checkcode() 方法名()import random # 导入包checkcode ""string range(0,4)for i in string:current random.randrange(0,3) #randrange随机数 参数1<随机数<参数2if current ! i:temp …

php haystack,haystack(示例代码)

1、haystack简介Haystack是django的开源全文搜索框架(全文检索不同于特定字段的模糊查询&#xff0c;使用全文检索的效率更高 )&#xff0c;该框架支持Solr,Elasticsearch,Whoosh, Xapian&#xff0c;搜索引擎它是一个可插拔的后端(很像Django的数据库层)&#xff0c;所以几乎你…

猫眼电影面试经历

面试是昨天上午进行的&#xff0c;因为昨天家里断网了&#xff0c;所以未能及时记录。 昨天的面试进行到了第三面&#xff0c;由于第三面的面试官当天未上班&#xff0c;所以成了回家等通知了。 感觉总体面试过程回答了百分之七十的样子吧&#xff01;一面、二面面试官都不错&a…

fopen php 乱码,如何解决php fgets读取文件乱码的问题

如何解决php fgets读取文件乱码的问题,文件,乱码,简体中文,记事本,页面如何解决php fgets读取文件乱码的问题易采站长站&#xff0c;站长之家为您整理了如何解决php fgets读取文件乱码的问题的相关内容。php fgets乱码的解决办法&#xff1a;首先依次点击“菜单修改->页面属…

一致性哈希算法原理分析及实现

一致性哈希算法常用于负载均衡中要求资源被均匀的分布到所有节点上&#xff0c;并且对资源的请求能快速路由到对应的节点上。具体的举两个场景的例子&#xff1a; 1、MemCache集群&#xff0c;要求存储各种数据均匀的存到集群中的各个节点上&#xff0c;访问这些数据时能快速的…

jsf集成spring_JSF – PrimeFaces和Hibernate集成项目

jsf集成spring本文介绍了如何使用JSF&#xff0c;PrimeFaces和Hibernate开发项目。 下面是一个示例应用程序&#xff1a; 二手技术&#xff1a; JDK 1.6.0_21 Maven的3.0.2 JSF 2.0.3 PrimeFaces 2.2.1 Hibernate3.6.7 MySQL Java连接器5.1.17 MySQL 5.5.8 Apache Tomcat 7.…

帝国 loginjs.php,帝国cms 6.6 后台拿shell

时间:2013-02-27来源:源码库 作者:源码库 文章热度:℃漏洞作者&#xff1a; 付弘雪提交时间&#xff1a; 2013-01-21公开时间&#xff1a; 2013-01-21漏洞类型&#xff1a; 文件上传导致任意代码执行简要描述&#xff1a;帝国cms 6.6版本后台拿shell 比网上流行的方法简单很多由…

合并两个排序的链表递归和非递归C++实现

题目描述&#xff1a; 输入两个单调递增的链表&#xff0c;输出两个链表合成后的链表&#xff0c;要求合成后的链表满足单调不减规则。 1、分析 已知输入的两个链表递增有序&#xff0c;要使输出的链表依然递增有序&#xff0c;可以依次从输入的两个链表中挑选最小的元素插入到…

带有JSF,Servlet和CDI的DynamicReports和JasperReports

在此示例中&#xff0c;我将展示如何将DynamicReport和JasperReports与Servlet和CDI集成。 工具&#xff1a; TIBCO Jaspersoft Studio-6.0.4。最终版 Eclipse Luna服务版本2&#xff08;4.4.2&#xff09;。 WildFly 8.x应用程序服务器。 这是Eclipse上项目层次结构的屏幕…

《Android进阶之光》--View体系与自定义View

No1&#xff1a; View的滑动 1&#xff09;layout()方法的 public class CustomView extends View{private int lastX;private int lastY;public CustomView(Context context,AttributeSet attrs,int defStyleAttr){super(context,attrs,defStyleAttr);}public CustomView(Cont…

js 数组 ajax php,js里面的对象ajax post到php端直接变成数组了?

本帖最后由 zhoumengkang 于 2013-09-12 10:03:14 编辑 事先引入了jqueryvar str "{a:b,aa:bb}";var str2 eval((str));var type typeof(str2);console.log(str);console.log(type);//objectconsole.log(str2);$.post(./bb.php,{data:str2});bb.php的代码$data $_…

【标签组件与图标 3.3】

1.图片图标。 SWing 利用javax.swing.ImageIcon 类根据现有图片创建图标&#xff0c;ImageIcon类实现了Icon接口&#xff0c;同时Java支持多种图片格式。 public ImageIcon&#xff08;&#xff09;:该构造方法创建了一个通用的ImageIcon对象&#xff0c;当正真需要设置图片时在…

swing 聊天气泡背景_Java Swing中的聊天气泡

swing 聊天气泡背景本文将向您解释“如何在Java swing应用程序中绘制聊天气泡&#xff1f;” 聊天气泡与呼出或提示气泡相同。 今天&#xff0c;大多数聊天应用程序都以这种格式显示转换&#xff0c;因此本文将帮助您在用Java swing创建的桌面应用程序中执行相同的操作。 以下课…

试述大数据对思维方式的重要影响

先讲大数据时代有哪些能做&#xff0c;哪些不能做&#xff1f;有一个很有名的科幻作家叫做阿西莫夫&#xff0c;写过《银河帝国》&#xff0c;也就是“基地系列”。据说本拉登就是看了他这本小说&#xff0c;把他自己的组织起名叫“基地组织”。阿西莫夫在书中提到&#xff0c;…