在是shiro自定义realm时,需要从数据库获取用户信息,用@Autowired注入的话,会引起多种问题,
例如:切换数据源报错,事务不生效等问题
从spring的工厂中获取可以解决问题
@Component
public class MyApplicationContext implements ApplicationContextAware {
public static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
MyApplicationContext.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
}
使用
UserService userService = (UserService) MyApplicationContextUtils.getBean("userService");