账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    为什么在Controller中对第三方Twitter类使用@Autowire注解无法自动注入?
    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"}),依然无法实现自动注入。
    请问这种情况,无疑实例代码是非常简洁的,到底是实例代码有错误,还是我的理解有错误?有没有解决办法?谢谢!

    1
    打赏
    收藏
    点击回答
        全部回答
    • 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的异常。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部