java静态工具类注入service出现NullPointerException异常处理

时间:2021-12-07 15:22:31

一般我们在controller层调用service时,只需要使用@Autowired注解即可,例如如下代码我们经常看到:

?
1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping("business")
public class BizResourceController {
    @Autowired
    private BusinessService businessService;
    @RequestMapping(path = "/queryYearList", method = RequestMethod.POST)
    public List<String> queryYearList(@RequestParam("cityCode") String cityCode) {
        return businessService.queryYearList(cityCode);
    }
}

以上代码的含义就是通过在controller中注入业务层类(BusinessService)调用业务层方法queryYearList。但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用@Autowired注解注入Service或者Mapper接口,直接注入是报错的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,当我们遇到这样的问题,我们就要想办法解决了。例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class RedisHelper {
    private static final Logger logger = LoggerFactory.getLogger(RedisHelper.class);
    @Autowired
    private static StringRedisTemplate redisTemplate;
 
    /**
     * scan 实现
     *
     * @param pattern  表达式
     * @param consumer 对迭代到的key进行操作
     */
    public static void scan(String pattern, Consumer<byte[]> consumer) {
        redisTemplate.execute((RedisConnection connection) -> {
            try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(Long.MAX_VALUE).match(pattern).build())) {
                cursor.forEachRemaining(consumer);
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    }
 
    /**
     * 获取符合条件的key
     *
     * @param pattern 表达式
     * @return
     */
    public static List<String> keys(String pattern) {
        List<String> keys = new ArrayList<>();
        scan(pattern, item -> {
            //符合条件的key
            String key = new String(item, StandardCharsets.UTF_8);
            keys.add(key);
        });
        return keys;
    }
 
    public static void delete(List<String> listKey) {
        try {
            logger.info("需要删除key:" + listKey);
            Long delete1 = redisTemplate.delete(listKey);
            logger.info("清除redis-key结果:{}",delete1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

如上代码在redis工具类中想要注入StringRedisTemplate但是我们使用的时候会发现,这个StringRedisTemplate对象时null。所以当我们需要有类似需求进行注入的时候要调整注入方式和写法,如下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
@Component
public class RedisHelper {
    private static final Logger logger = LoggerFactory.getLogger(RedisHelper.class);
    private static StringRedisTemplate redisTemplate;
 
    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        RedisHelper.redisTemplate = redisTemplate;
    }
 
    /**
     * scan 实现
     *
     * @param pattern  表达式
     * @param consumer 对迭代到的key进行操作
     */
    public static void scan(String pattern, Consumer<byte[]> consumer) {
        redisTemplate.execute((RedisConnection connection) -> {
            try (Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(Long.MAX_VALUE).match(pattern).build())) {
                cursor.forEachRemaining(consumer);
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });
    }
 
    /**
     * 获取符合条件的key
     *
     * @param pattern 表达式
     * @return
     */
    public static List<String> keys(String pattern) {
        List<String> keys = new ArrayList<>();
        scan(pattern, item -> {
            //符合条件的key
            String key = new String(item, StandardCharsets.UTF_8);
            keys.add(key);
        });
        return keys;
    }
 
    public static void delete(List<String> listKey) {
        try {
            logger.info("需要删除key:" + listKey);
            Long delete1 = redisTemplate.delete(listKey);
            logger.info("清除redis-key结果:{}",delete1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

其修改的核心是:

java静态工具类注入service出现NullPointerException异常处理

首先加@Component注解目的是让spring托管,另外注入StringRedisTemplate我们采用set方式进行注入即可。

到此这篇关于java静态工具类注入service出现NullPointerException异常处理的文章就介绍到这了,更多相关java静态类注入service出现NullPointerException处理内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://juejin.cn/post/7011387262924095524