若定义存在两个Service业务逻辑:
@Service
public class MyServiceImpl01 implements MyService {
@Override
public void demo() {
System.out.println("demo message 01");
}
}
@Service
public class MyServiceImpl02 implements MyService {
@Override
public void demo() {
System.out.println("demo message 02");
}
}
@SpringBootApplication
public class Application implements CommandLineRunner {
//默认通过名称进行注入
//若名称不存在,则通过类型注入 -> 高驼峰检索
@Resource
private MyService myService;
}
此时,myService类不存在 -> 转为高驼峰命名法( MyService
)进行Service业务逻辑层的检索( MyServiceImpl01
、MyServiceImpl02
)注入需要Bean的单例池模型,但发生多例重复Bean注入异常。
ERROR: expected single matching bean but found 2: myServiceImple01,myServiceImpl02
@SpringBootApplication
public class Application implements CommandLineRunner {
//默认通过类型进行注入
//若存在多个类型则通过名称进行注入
//-> 通过名称注入myServiceImpl02
@Autowired
private MyService myServiceImpl02;
}
可以通过注解 @Primary
或 @Qualifier
来指定注入某一个具体的业务逻辑:
@SpringBootApplication
public class Application implements CommandLineRunner {
//通过Qualifier指定注入muServiceImpl02接口实现类
@Autowired
@Qualifier("myServiceImpl02")
private MyService myService;
}
或在某一具体接口实现类上注入 @Primary
进行优先调用:
@Primary
@Service
public class MyServiceImpl01 implements MyService {
@Override
public void demo() {
System.out.println("demo message 01");
}
}