详谈@Autowired和static的关系
⽬录
@Autowired和static的关系
⼀、发⽣的场景
⼆、原理剖析 
三、解决⽅案
1、将@Autowire加到构造⽅法上
2、⽤@PostConstruct注解
static⽅法使⽤@Autowired
set注⼊失败构造器注⼊成功
@Autowired和static的关系
⼀、发⽣的场景
好⼏次有个同事因为把static⽤到Spring的@Autowired上,导致注⼊的对象⼀直报空指针,他⼀直不到错误在哪⾥,来问我,其实我以前也不知道这个问题,但我根据Spring容器的特点判定,他调⽤的对象与注⼊的对象不是⼀个对象,就告诉他:static的加载顺序是在@Autowired之前;之后查资料才知道其实不是这样。。。
⼆、原理剖析 
静态变量、类变量不是对象的属性,⽽是⼀个类的属性,所以静态⽅法是属于类(class)的,普通⽅法才是属于实体对象(也就是New出来的对象)的,spring注⼊是在容器中实例化对象,所以不能使⽤静态⽅法。
⽽使⽤静态变量、类变量扩⼤了静态⽅法的使⽤范围。静态⽅法在spring是不推荐使⽤的,依赖注⼊的主要⽬的,是让容器去产⽣⼀个对象的实例,然后在整个⽣命周期中使⽤他们,同时也让testing⼯作更加容易。
⼀旦你使⽤静态⽅法,就不再需要去产⽣这个类的实例,这会让testing变得更加困难,同时你也不能为⼀个给定的类,依靠注⼊⽅式去产⽣多个具有不同的依赖环境的实例,这种static field是隐含共享的,并且是⼀种global全局状态,Spring同样不推荐这样去做。
三、解决⽅案
1、将@Autowire加到构造⽅法上
@Component
public class Test {
private static UserService userService;
@Autowired
public Test(UserService userService) {
Test.userService = userService;
}
public static void test() {
}
}
2、⽤@PostConstruct注解
@Component
public class Test {
private static UserService userService;
@Autowired
private UserService userService2;
@PostConstruct
public void beforeInit() {
userService = userService2;
}
public static void test() {
}
}
static⽅法使⽤@Autowired
set注⼊失败构造器注⼊成功
@Component
@Slf4j
public class UserCookieInfoUtil {
private static RedisTemplate<String, String> redisTemplate;
private static JWTUtils jwtUtils;
@Autowired
public UserCookieInfoUtil(JWTUtils jwtUtils, RedisTemplate<String, String> redisTemplate) {
UserCookieInfoUtil.jwtUtils = jwtUtils;
}
public static Map<String, Object> getCookieInfo(String token) {
Map<String, Object> map = new HashMap<>();
try {
String loginName = LoginName(token);
String info = redisTemplate.opsForValue().get(Constants.TOKEN_USER_INFO + ":" + loginName);            map = JSONObject.parseObject(info == null ? "" : info, Map.class);
} catch (Exception e){
<("获取缓存中的登录信息失败:{}", e);
}
return map;
springboot原理pdf}
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。