您好我在我的项目中使用Spring Framwork,当我尝试自动连接两个接口时,我遇到了这个问题:错误:
Field metier in com.carpooling.metier.UserDetailsServiceImp required a single bean, but 2 were found:
- metierImp: defined in file [D:\eclipse_64\eclipse_64\eclipse\franceworkspace\Carpooling\target\classes\com\carpooling\metier\MetierImp.class]
- applicationModel: defined in file [D:\eclipse_64\eclipse_64\eclipse\franceworkspace\Carpooling\target\classes\com\carpooling\models\ApplicationModel.class]
代码:
@Component
public class ApplicationModel implements Metier {
@Autowired
private Metier metier;
private List<Mission> missions;
}
在我使用的其他文章中:
@Service
public class UserDetailsServiceImp implements UserDetailsService {
@Autowired
private Metier metier;
}
答案 0 :(得分:1)
问题是你有两个实现Metier
(ApplicationModel
和MetierImp
)的bean,所以spring不知道要注入哪个bean。
你有2个解决方案:
1. make one bean @Primary
- 这个注释告诉spring如果有多个候选者,选择用@Primary
注释的那个
2.使用@Qualifier
- 使用这个注释允许使用bean的名称告诉spring你想要注入哪个bean:
@Service
public class UserDetailsServiceImp implements UserDetailsService {
@Autowired
@Qualifier("applicationModel")
private Metier metier;
}
@Component
@Qualifier("applicationModel")
public class ApplicationModel implements Metier {
@Autowired
private Metier metier;
private List<Mission> missions;
}
如您所见,我使用ApplicationModel
注释命名@Qualifier
“applicationModel”,然后在UserDetailsServiceImp
中使用相同的注释告诉spring我想要ApplicationModel
被注射到那里。