zoukankan      html  css  js  c++  java
  • Spring @Autowired注解在非Controller中注入为null

    问题描述

    今天在写一个工具类,里面用了@Autowired注入了StringRedisTemplate以及RedisTemplate时,在template.opsForValue().set(key, obj)方法一直报 java.lang.nullpointerexception 异常,经过调试发现template为null。

    Spring 注入失败

    可能的原因: 网上百度了很久,原因可能在于我的utils包的类和controller的类不是同一个上下文。

    解决办法

    通过添加以下三个关键的地方,可以解决该问题

    关于@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。
    //解决工具类中注入 3个步骤
    @Component                     //关键步骤1,添加Component
    public class RedisUtils {
        
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
        @Autowired
        private RedisTemplate<String, Object> template;
        
        public static RedisUtils redisUtils;          // 关键2 添加该类的静态对象
        protected static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
        
        public RedisUtils() {
        }
        
        // 关键3 用PostConstruct修饰init方法,并在init方法中对其赋值
        @PostConstruct
        public void init() {
            redisUtils = this;
            redisUtils.template = this.template;
            redisUtils.stringRedisTemplate = this.stringRedisTemplate;
        }
        

    这样就可以通过redisUtils.template.opsForValue().set(key, obj)调用了

  • 相关阅读:
    游戏引擎架构笔记之开篇
    Hacker(六)----黑客藏匿之地--系统进程
    Hacker(五)----黑客专用通道--->端口
    Hacker(四)----查看计算机的IP地址
    Hacker(三)之黑客定位目标---IP
    黑客必备技能
    黑客和骇客
    上海公积金提取办法(外地购房,公积金在上海)
    Python入门-----Windows安装
    Python入门-----介绍
  • 原文地址:https://www.cnblogs.com/zhangyongJava/p/9375483.html
Copyright © 2011-2022 走看看