UserRealm中注入UserService方法和事务失效的解决方法
在使用shiro时,ShiroFilterFactoryBean 会依赖注入 securityManager 然后 securityManager 会注入自定义 Realm ,然后自定义Realm类里面会注入业务的service类,而那些service类包含事务,都是动态代理类。因此无法注入,大致异常为:xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)。 由于shiro的bean先于Spring事务将userService实例化了,结果导致spring事务初始化时好无法扫描到该bean,导致这个bean上没有绑定事务,导致事务无效,报错如下:
一,xxxx is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)解决
1.在字段上加@Lazy(推荐)
import org. springframework. context. annotation. Lazy ;
import org. apache. shiro. realm. AuthorizingRealm ;
public class DatabaseRealm extends AuthorizingRealm {
@Lazy
@Autowired
private UserService userService;
2.加到构造方法的参数上
import org. springframework. context. annotation. Lazy ;
import org. apache. shiro. realm. AuthorizingRealm ;
public class DatabaseRealm extends AuthorizingRealm {
private UserService userService;
public DatabaseRealm ( @Lazy @Autowired UserService userService) {
this . userService = userService;
}
}
3.使用hutool工具类下的SpringUtil
@Override
protected AuthenticationInfo doGetAuthenticationInfo ( AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken userToken = ( UsernamePasswordToken ) authenticationToken;
MUserService userService = SpringUtil . getBean ( MUserService . class ) ;
MUser user = userService. getOneUser ( userToken. getUsername ( ) ) ;
if ( user == null ) {
throw new UnknownAccountException ( "账户不存在" ) ;
}
if ( ! String . valueOf ( userToken. getPassword ( ) ) . equals ( user. getPassword ( ) ) ) {
throw new IncorrectCredentialsException ( "密码错误" ) ;
}
return new SimpleAuthenticationInfo ( user, user. getPassword ( ) , getName ( ) ) ;
}
4.在Shiro框架中注入Bean时,不使用@Autowire,使用ApplicationContextRegister.getBean()方法,手动注入bean。保证该方法只有在程序完全启动运行时,才被注入
二,事务失效解决方法
1.在字段上加@Lazy(推荐)
import org. springframework. context. annotation. Lazy ;
import org. apache. shiro. realm. AuthorizingRealm ;
public class DatabaseRealm extends AuthorizingRealm {
@Lazy
@Autowired
private UserService userService;
2.orm映射框架的Mapper类,不是由Spring生成初始化,只是交给Spring管理,不会影响Spring bean的初始化
public class UserRealm extends AuthorizingRealm {
private static final Logger LOGGER = LoggerFactory . getLogger ( UserRealm . class ) ;
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysPermissionMapper sysPermissionMapper;
}
3.在service实现层的类或者public方法上添加@Transactionl注解