A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

1.demo1-1.接口定义  包名:com.example.demo        接口:ITestpackage 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;@Componentpublic 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;@Componentpublic 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") -------> 运行成功


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马