官網(wǎng)的解釋:Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value
意思就是說(shuō)當(dāng)一個(gè)bean有多個(gè)候選者返奉,則會(huì)挑選被標(biāo)注為@Primary的bean驳棱,否則會(huì)報(bào)錯(cuò)
/** 定義一個(gè)接口 */
public interface UserServiceImpl {
public void fun();
}
@Primary
@Component
public class BossUserServiceImpl implements UserServiceImpl {
@Override
public void fun() {
System.out.println("i'm boss service implement");
}
}
@Component
public class EmployeeUserServiceImpl implements UserServiceImpl {
@Override
public void fun() {
System.out.println("i'm employee service implement");
}
}
定義一個(gè)接口蘑拯,并且有兩個(gè)實(shí)現(xiàn)類,然后再定義一個(gè)bean,注入該接口
@Service
public class UserService {
@Autowired
private UserServiceImpl userServiceImpl;
public void fun() {
userServiceImpl.fun();
}
}
定義一個(gè)配置類,去掃描這些bean
@Configuration
@ComponentScan("com.sendo.spring")
public class BeanConfig {
}
運(yùn)行測(cè)試:
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
UserService userService = context.getBean(UserService.class);
userService.fun();
}
結(jié)果:
Connected to the target VM, address: '127.0.0.1:56659', transport: 'socket'
Nov 16, 2018 3:44:58 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6b143ee9: startup date [Fri Nov 16 15:44:58 CST 2018]; root of context hierarchy
i'm boss service implement
Disconnected from the target VM, address: '127.0.0.1:56659', transport: 'socket'