之前写一个工具类,需要在static方法中读取db数据进行判断,但发现静态mapper按照正常的写法是无法注入的,最后Google后解决问题,代码如下:
@Service
public class TestUtil {
private static UserMapper userMapper;
@Autowired
public void setUserMapper(UserMapper userMapper) {
TestUtil.userMapper = userMapper;
}
public static void getUsetList(){
List<User> users = userMapper.getUserList(null);
System.out.println(users.size());
}
}
其实也没什么不一样,主要的注意点在于
- 类名上增加一个@Service注解
- @Autowired注解放到了set方法上
- Set方法static关键字一定要删除(eclipse默认的set get方法补全是有static关键字的)
另一种方法是通过applicationContext.xml进行注入,但使用起来不如@Autowired方便,所以不推荐使用。