记录@ConditionalOnMissBean注解不正确使用引发的依赖注入问题
伪代码如下:
public interface UserInfoService {}
@Service
public class BusinessUserInfoService implemenets UserInfoService {
}
@Configuration
public XConfiguration {
@Bean
@ConditionalOnMissBean
public UserInfoService userInfoService() {
return new SystemUserInfoService();
}
@Bean
public UserInfoManager userInfoManager() {
UserInfoService userInfoService = userInfoService();
UserInfoManager manager = new UserInfoManager(userInfoService);
return manager;
}
}
如上代码,在Spring应用启动时会报找不到userInfoServie的错误,原因是userInfoService被@Bean注解和@ConditionalOnMissBean注解同时修饰,而且容器中已经存在UserInfoService的一个子类实例BusinessUserInfoService,所以SystemUserInfoService的实例将不再被放入Spring容器;
而userInfoManager()内调用的userInfoService()实际上调用的是Spring为XConfiguration生成的代理类上的方法,所以userInfoService的调用相当于从Spring容器中以userInfoService为name获取bean,而实际上容器中存在的只有一个名为businessUserInfoService的bean,所以提示无法找到userInfoService。

浙公网安备 33010602011771号