背景: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()