SpringBoot提供了许多启动器模块来快速启动和运行。 SpringBoot的自动配置机制负责根据各种标准代表我们配置SpringBean。
除了Core Spring Team提供的现成的springboot启动器之外,我们还可以创建自己的启动器模块。
在本文中,我们将研究如何创建自定义的SpringBoot启动器。 为了演示它,我们将创建twitter4j-spring-boot-starter ,它将自动配置Twitter4J bean。
为此,我们将创建:
- twitter4j-spring-boot-autoconfigure模块,其中包含Twitter4J AutoConfiguration bean定义
- twitter4j-spring-boot-starter模块,用于获取twitter4j-spring-boot-autoconfigure和twitter4j-core依赖项
- 使用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.0
http://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-autoconfigure , twitter4j-core和junit ,如下所示:
<?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.0
http://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;
@NestedConfigurationProperty
private 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);
@Autowired
private Twitter4jProperties properties;
@Bean
@ConditionalOnMissingBean
public 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
@ConditionalOnMissingBean
public 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.0
http://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.0
http://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 {
@Autowired
private 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 {
@Autowired
private TweetService tweetService;
@Test
public 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