Posting a Twitter4j Twitter class in Spring
I only need one instance of Twitter class in Twitter4j in Spring container. My problem is I can't see a way to set the oauth user in the Twitter class. As far as I know, you can only use the setter method, which only takes one parameter. Not two. For example, there are thoughts that I cannot connect something like this:
Twitter twitter = new Twitter();
twitter.setOAuthConsumer([consumer key],[consumer secret]);
Of course I want to avoid hard-coding the consumer key and consumer secrets that win using DI I think.
My solution is to encapsulate the twitter class in another class so that I can alternately associate the consumer key and consumer secret:
public class TwitterAuth {
private Twitter twitter;
public TwitterAuth(Twitter twitter, consumerKey, consumerSecret) {
this.twitter=twitter;
twitter.setOauthConsumer(consumerKey,consumerSecret);
}
public void getTwitter(){
return twitter;
}
}
Although he solves my problem, he introduces me to another. I no longer need TwitterAuth when the twitter class is introduced. How do I opt out of TwitterAuth?
Better still is there a better way to link this? Thank you! :)
source to share
I no longer need TwitterAuth after entering the twitter class. How do I opt out of TwitterAuth?
I wouldn't worry about the drop TwitterAuth
. When there are no references to it, garbage will eventually be collected. In any case, it doesn't have a lot of memory.
You don't need your code to depend on TwiterAuth
. Instead, you can tell Spring to create an object Twitter
using the instance factory method . First, you need to make a small modification in TwitterAuth
order to create an object Twitter
:
public class TwitterAuth {
private final Twitter twitter;
public TwitterAuth(String consumerKey, String consumerSecret) {
this.twitter = new Twitter();
twitter.setOauthConsumer(consumerKey, consumerSecret);
}
public Twitter getTwitter() {
return twitter;
}
}
If the bean name for TwitterAuth
is "twitterAuth"
, then this XML will set up TwitterAuth.getTwitter()
as a factory method:
<bean id="twitter"
factory-bean="twitterAuth"
factory-method="getTwitter"/>
Then you can inject the object Twitter
into your classes directly, instead of having the classes depend on TwitterAuth
. The installation of the constructor and setter for TwitterAuth
will be done before Spring calls the method getTwitter()
.
Instead of using a factory instance method, you can change TwitterAuth
to implement the FactoryBean . The advantage is slightly less XML. The disadvantage is the Java source code that will be more tied to Spring.
source to share