1、首先声明MyService接口和两个实现类MyServiceImpl01和MyServiceImpl02
public interface MyService {
void hello();
}
@Service
public class MyServiceImpl01 implements MyService{
@Override
public void hello() {
System.out.println("MyServiceImpl01 print hello!");
}
}
@Service
public class MyServiceImpl02 implements MyService{
@Override
public void hello() {
System.out.println("MyServiceImpl02 print hello!");
}
}
2、测试方法:
@SpringBootApplication
public class AprilApplication implements CommandLineRunner {
@Resource
private MyService myService;
@Override
public void run(String... args) {
myService.hello();
}
public static void main(String[] args) {
SpringApplication.run(AprilApplication.class, args);
}
}
3、@Resource解决方案:
@SpringBootApplication
public class AprilApplication implements CommandLineRunner {
@Resource
private MyService myServiceImpl01;
@Override
public void run(String... args) {
myServiceImpl01.hello();
}
public static void main(String[] args) {
SpringApplication.run(AprilApplication.class, args);
}
}
控制台输出:
MyServiceImpl01 print hello!
4、@Autowired
@SpringBootApplication
public class AprilApplication implements CommandLineRunner {
@Autowired
private MyService myService;
@Override
public void run(String... args) {
myService.hello();
}
public static void main(String[] args) {
SpringApplication.run(AprilApplication.class, args);
}
}
5、@Autowired解决方案:指定名称注入
@SpringBootApplication
public class AprilApplication implements CommandLineRunner {
@Autowired
private MyService myServiceImpl01;
@Autowired
@Qualifier("myServiceImpl02")
private MyService myService;
@Override
public void run(String... args) {
myServiceImpl01.hello();
myService.hello();
}
public static void main(String[] args) {
SpringApplication.run(AprilApplication.class, args);
}
}
控制台输出:
MyServiceImpl01 print hello!
MyServiceImpl02 print hello!