Spring之@Primary、 @Qualifier解决多实现选主问题

OrderService

@Component
public class OrderService {
    @Autowired
    //方式一
    @Qualifier("userServiceImpl01")
    private UserService userService;

    public void print() {
        userService.print();
    }
}

UserService

public interface UserService {
    public void print();
}

UserServiceImpl01

@Service
//方式二
//@Primary
public class UserServiceImpl01 implements UserService {
    public void print() {
        System.out.println("this is 01");
    }
}

UserServiceImpl02

@Service
public class UserServiceImpl02  implements UserService {
    public void print() {
        System.out.println("this is 02");
    }
}

MyConfig
以上类都在com.whotw包里

@Configuration
@ComponentScan("com.whotw")
public class MyConfig {
}
WhotwDemo 
public class WhotwDemo {

    public static void main(String[] args) {
        System.out.println("启动成功");
//        ClassPathXmlApplicationContext
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        OrderService orderService = (OrderService) applicationContext.getBean("orderService");
        orderService.print();
    }
}

你可能感兴趣的:(Spring之@Primary、 @Qualifier解决多实现选主问题)