@Component下@Autowired注入为null的问题

您所在的位置:网站首页 bean为null @Component下@Autowired注入为null的问题

@Component下@Autowired注入为null的问题

2023-07-27 05:01| 来源: 网络整理| 查看: 265

前言

这个问题是无意中发现的,之前也没有一直太注意这块,今天突然遇到了就作个记录。

请看错误代码, 使用@Component注入非@Controller和@Service等类的注入,使用@Autowired进行属性注入。

@Component public class UserWrapper extends BaseEntityWrapper { @Autowired private RoleMapper roleMapper; @Autowired private PermissionMapper permissionMapper; public static UserWrapper build() { return new UserWrapper(); } @Override public UserVo entityVO(User user) { UserVo userVo = new UserVo(); if (user != null) { try { userVo = BeanUtil.copyFromFather(user,userVo); } catch (Exception e) { e.printStackTrace(); } List roles = roleMapper.findRoleByUserId(user.getId()); List permissions = new ArrayList(); for (Role role : roles) { for (Permission permission :permissionMapper.findPermissionListByRoleId(role.getId())) { permissions.add(permission); } } userVo.setPermissionList(permissions); userVo.setRoleList(roles); } return userVo; }

测试代码:

System.out.println("==============="+UserWrapper.build().entityVO(user).toString());

发现报错 在这里插入图片描述 也就是注入失败了。

关于这两个组合下出现此问题的原因(个人见解):对于一般的类我们直接new出来就可以了,但是带有上述这两注解的类,如果new出来的话那么注入的属性就会为null。

目前使用的解决办法:

@Component public class UserWrapper extends BaseEntityWrapper { @Autowired private RoleMapper roleMapper; @Autowired private PermissionMapper permissionMapper; //声明一个静态变量来存储 public static UserWrapper userWrapper; public static UserWrapper build() { return userWrapper; } @PostConstruct public void init(){ userWrapper = this; } @Override public UserVo entityVO(User user) { UserVo userVo = new UserVo(); if (user != null) { try { userVo = BeanUtil.copyFromFather(user,userVo); } catch (Exception e) { e.printStackTrace(); } List roles = roleMapper.findRoleByUserId(user.getId()); List permissions = new ArrayList(); for (Role role : roles) { for (Permission permission :permissionMapper.findPermissionListByRoleId(role.getId())) { permissions.add(permission); } } userVo.setPermissionList(permissions); userVo.setRoleList(roles); } return userVo; } }

增添的方法:

@PostConstruct public void init(){ userWrapper = this; }

使用**@PostConstruct** 对进行赋值,该注解的作用是 只要该类被Spring管理了就会立即执行带有这个直接的方法。

修改的方法:

public static UserWrapper build() { return userWrapper; }

修改之前使用new来创建并返回一个对象的操作,直接返回静态属性。

这样就不会在出现注入失败的问题了,至于具体为什么new会出现null目前还没有搞明白,希望各位大佬指点一下,在此感谢!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3