- 35
- 0
这个问题来自于《master springMVC 4》这本书的源码,用SpirngBoot 2搭建的环境,根据我的理解,@Autowired注解一般无法对第三方包下面的类直接进行注入(我们无法保证第三方提供的类已经加上@Component,并且包路径可以被自动扫描),实例中对org.springframework.social.twitter.api.Twitter接口加了@Autowired注解,其实现类为TwitterTemplate,构造方法的两个参数TwitterTemplate(key,secretToken)来自于Application.properties的配置,根据实际测试,下面的代码不能正常工作。
代码如下:
package com.labs.app.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.twitter.api.SearchOperations;
import org.springframework.social.twitter.api.SearchResults;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
public class TweetController {
@Autowired
private Twitter twitter;
@RequestMapping("/")
public String hello(@RequestParam(defaultValue="sb01") String search, Model model){
SearchOperations so = twitter.searchOperations();
String text = "INIT";
if(null!=so){
SearchResults sr = so.search(search);
text = sr.getTweets().get(0).getText();
}
model.addAttribute("message", text);
return "resultPage";
}
}
得到的错误信息如下:
Description:
Field twitter in com.labs.drivingschool.controller.TweetController required a bean of type 'org.springframework.social.twitter.api.Twitter' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.social.twitter.api.Twitter' in your configuration.
尝试的做法
尝试对@SpringBootApplication加上(baseScanPackages={"xxxxxx"}),依然无法实现自动注入。
请问这种情况,无疑实例代码是非常简洁的,到底是实例代码有错误,还是我的理解有错误?有没有解决办法?谢谢!
- 共 0 条
- 全部回答
-
-何必执着。 普通会员 1楼
在Spring框架中,如果第三方类依赖于Twitter类,那么需要通过@Autowired注解来自动注入这个第三方类。
@Autowire注解用于自动初始化由@Autowired注解定义的Bean。但是,如果第三方类依赖于Twitter类,那么它也需要有一个@Service或@Component注解,该注解指定这个类应该是一个服务或组件。
例如,如果你有一个Twitter类TwitterService,你需要在TwitterService的@Service注解中使用@Autowired注解来自动注入Twitter类。如果你有一个Twitter类TwitterComponent,你需要在TwitterComponent的@Component注解中使用@Autowired注解来自动注入Twitter类。
如果你的第三方类Twitter 类有@Service或@Component注解,那么Spring框架会自动注入Twitter类。如果你的第三方类Twitter类没有@Service或@Component注解,那么Spring框架会抛出一个找不到Bean的异常。
- 扫一扫访问手机版
回答动态

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器更新之后。服务器里面有部分玩家要重新创建角色是怎么回事啊?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题函数计算不同地域的是不能用内网吧?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题ARMS可以创建多个应用嘛?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题在ARMS如何申请加入公测呀?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题前端小程序接入这个arms具体是如何接入监控的,这个init方法在哪里进行添加?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器刚到期,是不是就不能再导出存档了呢?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器的游戏版本不兼容 尝试更新怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器服务器升级以后 就链接不上了,怎么办?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器转移以后服务器进不去了,怎么解决?预计能赚取 0积分收益

- 神奇的四哥:发布了悬赏问题阿里云幻兽帕鲁服务器修改参数后游戏进入不了,是什么情况?预计能赚取 0积分收益
- 回到顶部
- 回到顶部
