解决required a single bean, but 2 were found问题
一、背景
springboot整合shiro中自定义Realm时出现
错误描述
Parameter 0 of method getDefaultWebSecurityManager in cn.ken.springboot_shiro.config.ShiroConfig required a single bean, but 2 were found:
- getRealm: defined by method ‘getRealm’ in class path resource [cn/ken/springboot_shiro/config/ShiroConfig.class]
- iniClasspathRealm: defined by method ‘iniClasspathRealm’ in class path resource [org/apache/shiro/spring/boot/autoconfigure/ShiroAutoConfiguration.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
二、场景再现
// 创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
// 给安全管理器设置realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
错误分析:容器中出现了两个Realm类型的Bean,注入时不知道选择哪一个
三、解决
在参数中注入Realm时指定bean的id以区分
// 创建安全管理器
@Bean
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
// 给安全管理器设置realm
defaultWebSecurityManager.setRealm(realm);
return defaultWebSecurityManager;
}
// 创建自定义Realm
@Bean
public Realm getRealm(){
return new CustomerRealm();
}
@Qualifier(“getRealm”)参数之所以为getRealm是因为下面@Bean的方法名为getRealm()
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 Ken·勇者の小栈
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果