静态方法中调用mybatis内容自动注入@Autowired,同样适用自动注入非静态类在静态方法中调用
通常使用mybatis是直接使用自动装配的service类来完成的,但是如果想要在静态方法中使用service类是不行的,静态方法无法使用非静态的类成员变量,并且自动装配无法对静态成员变量使用,所以需要做一个中转:
public class TestService {
private static TargetService staticTargetService;
@Autowired
private TargetService targetService;
@PostContruct
private void init() {
staticTargetService = targetService;
}
public static Object test(String id) {
return staticTargetService.getAllById(id);
}
}