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

twitter自定义api

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

twitter自定义api

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

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

相关文章

LeetCode 面试题 03 数组中重复的数字

原题链接 标签: 数组 集合 解题思路&#xff0c;找到数组中重复的任何一个元素。所以直接创建一个Set就解决了 class Solution {public int findRepeatNumber(int[] nums) {Set<Integer> numsSet new HashSet<>();for(int num: nums) {if(!numsSet.add(num))…

eclipse neon_在自定义Java 9映像上运行Eclipse Neon

eclipse neon我已经开始修改自定义Java二进制运行时映像文件。 映像文件是打包为运行时平台的模块的配置。 基本上&#xff0c;默认映像包含组成Java运行时的所有内容。 自定义图像可以包含该图像的一些子集。 例如&#xff0c;我创建了一个仅包含“ compact 3”概要文件的映像…

java json注解_返回json用什么注解

返回json用“ResponseBody”注解&#xff0c;“ResponseBody”是作用在方法上的&#xff0c;“ResponseBody”表示该方法的返回结果直接写入“HTTP response body”中。本篇文章将介绍两种示例进行JSON返回注解方式演示。示例1ResponseBody是作用在方法上的&#xff0c;Respons…

LeetCode 662 二叉树最大宽度

原题链接 标签 &#xff1a;二叉树 BFS 解题思路&#xff1a;BFS广度优先 队列 /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* …

mockito 静态_在Java 8中使用不带静态导入的Mockito

mockito 静态如何通过在基于Java 8的项目中删除静态导入来简化Mockito的使用。 基本原理 Mockito API基于&#xff08;BDD&#xff09;Mockito类中聚集的静态方法&#xff08;大部分&#xff09;&#xff0c;然后进行非常流畅的链接方法调用。 可以使用模拟/间谍/给定/然后/验…

LeetCode 15 二进制中1的个数

原题 解题思路: 位运算 eor & -eor eor & (~eor 1) 取出数中最后一位的操作 class Solution { public:int hammingWeight(uint32_t n) {int ret0;while(n){n-(n & -n);//每次减n最后一位1 &#xff0c;减了多少次。就有多少个1ret;} return ret;} };…

java实现未读消息提醒_Android自定义View之未读消息提示

一个轻量级的仿微信未读消息提示大家好&#xff0c;我是接触安卓不久的小菜鸟&#xff0c;今天花了一晚上封装了一个类似微信未读消息提示的安卓控件。由于技术问题&#xff0c;所以功能不是很强大&#xff0c;没有动画&#xff0c;但是满足基本需求还是可以的。下面是示例图&a…

java 拼图_拼图推迟将Java 9的发布日期推迟到2017年

java 拼图由于Project Jigsaw的延迟&#xff0c;Java 9的发布日期被推迟到2017年 由于项目延迟的悠久历史&#xff0c;这可能不足为奇&#xff0c;但是看起来备受期待的拼图项目已被延迟。 再次。 好消息是&#xff0c;与上一次使用Java 8不同&#xff0c;它仍在Java 9的开发路…

java数据结构博客园_常见数据结构的Java实现

单链表的Java实现首先参考wiki上的单链表说明&#xff0c;单链表每个节点包含数据和指向链表中下一个节点的指针或引用。然后看代码import java.lang.*;public class SinglyLinkeList{Node start;public SinnglyLinkedList(){this.startnull;}public void addFront(Object newD…

jboss4 java_带有JBoss工具的OpenShift 3上的Java EE 7应用程序

jboss4 java您可以使用最新版本的JBoss Tools OpenShift插件在Eclipse中创建和管理OpenShift应用程序。 他们要么预先捆绑了最新的 JBoss Developer Studio&#xff08;9.0.0.GA&#xff09; &#xff0c;也可以将它们安装到现有的Eclipse Mars中。 这篇文章将引导您通过JBoss…

LeetCode 876. 链表的中间结点

原题链接 解题思路:快慢指针&#xff0c;快指针走两步&#xff0c;慢指针走一步。快指针到NULL慢指针自然到中间位置 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/…

Java读取类路径下的JSON文件并转换为实体列表

使用 Jackson 库来读取类路径下的 JSON 文件并将其转换为对应实体列表。 在实际开发中可能在本地环境中需要调用别人的接口&#xff0c;别人的接口如果还没开发好或者本地环境不支持外部接口调用的时候&#xff0c;可以读取json文件来造数据&#xff0c;方便调试。 以Student…

java安全点_关于OopMap、SafePoint(安全点)以及安全区域

1.OopMap之前我们提到&#xff0c;在正式的GC之前总是需要进行可达性分析来查找内存中所有存活的对象&#xff0c;以便GC能够正确的回收已经死亡的对象。那么对于一个十分复杂的系统&#xff0c;每次GC的时候都要遍历所有的引用肯定是不现实的。因为在可达性分析的时候&#xf…

javaslang_使用Javaslang的Java 8中的功能数据结构

javaslangJava 8的lambda&#xff08;λ&#xff09;使我们能够创建出色的API。 它们极大地提高了语言的表达能力。 Javaslang利用lambda来基于功能模式创建各种新功能。 其中之一是功能性集合库&#xff0c;旨在替代Java的标准集合。 &#xff08;这只是鸟瞰图&#xff0c;您…

LeetCode 面试题 链表中倒数第K个点

解题思路&#xff0c;倒数第K个点&#xff0c;位于正数N-K1的位置。 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:ListNode* getKthFromEn…

java调用kafka接口发送数据_Java调用Kafka生产者,消费者Api及相关配置说明

本次的记录内容包括&#xff1a;1.Java调用生产者APi流程2.Kafka生产者Api的使用及说明3.Kafka消费者Api的使用及说明4.Kafka消费者自动提交Offset和手动提交Offset5.自定义生产者的拦截器&#xff0c;分区器那么接下来我就带大家熟悉以上Kafka的知识说明1.Java调用生产者APi流…

java中的方法求和_在Java中模拟求和类型的巧妙解决方法

java中的方法求和在继续阅读实际文章之前&#xff0c;我想感谢令人敬畏的Javaslang库的作者Daniel Dietrich &#xff0c;他在我面前有了这个主意&#xff1a; lukaseder尝试使用静态方法<T&#xff0c;T1扩展T&#xff0c;... Tn扩展T> Seq <T> toSeq&#xff08…

java如何模拟请求_单元测试如何模拟用户请求

python web自动化测试设计构工具书40.9元包邮(需用券)去购买 >错误正当我高高兴兴写完后台c层的测试代码准备提交时&#xff0c;测试机器人报了很多401错误&#xff0c;把代码拉下来一看&#xff0c;原来当我写代码时&#xff0c;我的伙伴已经写好后台的拦截器了&#xff0c…

LeetCode 237. 删除链表中的节点

原题链接 解题思路&#xff1a;后面的的结点内容覆盖前面的结点内容 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:void deleteNode(ListN…

java异步接口转同步接口_如果今天设计了Java:同步接口

java异步接口转同步接口Java已经走了很长一段路。 很长的路要走。 它带有早期设计决策中的所有“垃圾”。 一遍又一遍后悔的一件事是&#xff0c; 每个对象&#xff08;可能&#xff09;都包含一个监视器 。 几乎没有必要这样做&#xff0c;并且最终在Java 5中纠正了该缺陷&am…