注意事项:
- 静态方法中只能调用静态成员和静态方法
- 如果使用@autowired或者@resource注解自动注入,所定义的静态成员service为null, 无法实现直接注入对象
静态方法调用service报空指针解决方案:
- 工具类需要实现初始化接口,并交给spring管理
- 创建静态成员变量service
- 创建公共成员变量service,并实现自动注入
- 重写初始化方法,在方法里将公共成员变量赋值给静态成员变量
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BasicController implements InitializingBean {
// 静态成员变量
private static ZnChuangxinPersonService staticChuangxinPersonService;
private static ZnChuangxinOrgService staticChuangxinOrgService;
// 公共成员变量
@Autowired
private ZnChuangxinPersonService znChuangxinPersonService;
@Autowired
private ZnChuangxinOrgService znChuangxinOrgService;
// 重写初始化方法
@Override
public void afterPropertiesSet() throws Exception {
staticChuangxinOrgService = znChuangxinOrgService;
staticChuangxinPersonService = znChuangxinPersonService;
}
// 静态方法中调用service
public static String getCurrentUnionId() {
String loginName = getCurrentUserLoginName();
ZnChuangxinPerson person = staticChuangxinPersonService.fingByJobNum(loginName);
ZnChuangxinOrg org = staticChuangxinOrgService.getOne(person.getCxorgId().getId());
return org == null ? "" : org.getUnionId();
}
}