欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决static静态方法无法使用@Autowired注入的mapper/bean等元的问题

程序员文章站 2022-03-23 23:17:09
...

解决static静态方法无法使用@Autowired注入的mapper/bean等元的问题

[email protected]注入元素

@Autowired注入元素时,得一次性注入两个元素,一个是静态的,一个不是静态的。

@Autowired
    private UserMapper testUserMapper; //非静态
    private static UserMapper userMapper; //静态

    @Autowired
    private RoleMapper testRoleMapper; //非静态
    private static RoleMapper roleMapper; //静态

2.编写init方法

编写init方法将非静态的元素初始化给静态元素,这样在静态方法中,就可以调用静态的那个元素。

@PostConstruct
    public void init() {
        userRoleMapper = this.testUserRoleMapper;
        roleMapper = this.testRoleMapper;
    }

3.完整代码

@Component
public class GetRoleByUserNameUtil {
    @Autowired
    private UserRoleMapper testUserRoleMapper;
    private static UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper testRoleMapper;
    private static RoleMapper roleMapper;


    @PostConstruct
    public void init() {
        userRoleMapper = this.testUserRoleMapper;
        roleMapper = this.testRoleMapper;
    }

    public static String getRoleByUserName(String userName) {
        UserRole userRole = new UserRole();
        Role role = new Role();

        //UserRole 的条件构造器
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.inSql("userID",
                "select userID from user where userName = '" + userName + "'");

        userRole = userRoleMapper.selectOne(wrapper);

        //Role的条件构造器
        QueryWrapper<Role> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("roleID", userRole.getRoleID());

        role = roleMapper.selectOne(wrapper1);
        return role.getRoleName();
    }
}