Tian戊辰 2018-08-10 07:53 采纳率: 100%
浏览 3127
已采纳

求助:springboot中接口和实现类不在同一个jar中,@Autowired失败

1.demo

1-1.接口定义

  包名:com.example.demo
        接口:ITest
package com.example.demo;

public interface ITest {

  void find();
}

1.2.接口使用

@Autowired
@Qualifier("myTest2") // ←自动注入不同的实现类
private ITest itest;

// 调用实现类的方法
itest.find();

1.3.同一jar中定义实现类

package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MyTest2 implements ITest {

  private static final Logger LOGGER = LoggerFactory.getLogger(MyTest2.class);

  @Override
  public void find() {
    LOGGER.info("MyTest2#find");    
  }
}

2.demo01

在其他jar中定义实现类【**包名相同**】

package com.example.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class MyTest implements ITest {

  private static final Logger LOGGER = LoggerFactory.getLogger(MyTest.class);

  @Override
  public void find() {
    LOGGER.info("MyTest#find");
  }
}

注)Springboot入口类:

@SpringBootApplication(scanBasePackages = { "com.example" })
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

然后修改上面【1.2.接口使用】中@Qualifier的实现类,运行后发现:
1.@Qualifier("myTest") -------> 运行失败,错误如下:


APPLICATION FAILED TO START


Description:

Field itest in com.example.demo.MyRunner required a bean of type 'com.example.demo.ITest' that could not be found.

Action:

Consider defining a bean of type 'com.example.demo.ITest' in your configuration.

2.@Qualifier("myTest2") -------> 运行成功

  • 写回答

3条回答 默认 最新

  • 默默a20 2018-08-10 09:28
    关注

    你是maven 多模块开发吧,入口类所在的包引入另外一个模块的进来了吗

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义