一般我们在controller层调用service时,只需要使用Autowired注解即可,例如如下代码我们经常看到:RestControllerRequestMapping(business)publicclassBizResourceController{AutowiredprivateBusinessServicebusinessService;RequestMapping(pathqueryYearList,methodRequestMethod。POST)publicListStringqueryYearList(RequestParam(cityCode)StringcityCode){returnbusinessService。queryYearList(cityCode);}} 以上代码的含义就是通过在controller中注入业务层类(BusinessService)调用业务层方法queryYearList。但是如果我们要在我们自己封装的Utils工具类中或者非controller普通类中使用Autowired注解注入Service或者Mapper接口,直接注入是报错的,因为Utils使用了静态的方法,我们是无法直接使用非静态接口的,当我们遇到这样的问题,我们就要想办法解决了。例如:publicclassRedisHelper{privatestaticfinalLoggerloggerLoggerFactory。getLogger(RedisHelper。class);AutowiredprivatestaticStringRedisTemplateredisTemplate;scan实现parampattern表达式paramconsumer对迭代到的key进行操作publicstaticvoidscan(Stringpattern,Consumerbyte〔〕consumer){redisTemplate。execute((RedisConnectionconnection){try(Cursorbyte〔〕cursorconnection。scan(ScanOptions。scanOptions()。count(Long。MAXVALUE)。match(pattern)。build())){cursor。forEachRemaining(consumer);returnnull;}catch(IOExceptione){e。printStackTrace();thrownewRuntimeException(e);}});}获取符合条件的keyparampattern表达式returnpublicstaticListStringkeys(Stringpattern){ListStringkeysnewArrayList();scan(pattern,item{符合条件的keyStringkeynewString(item,StandardCharsets。UTF8);keys。add(key);});returnkeys;}publicstaticvoiddelete(ListStringlistKey){try{logger。info(需要删除key:listKey);Longdelete1redisTemplate。delete(listKey);logger。info(清除rediskey结果:{},delete1);}catch(Exceptione){e。printStackTrace();}}} 如上代码在redis工具类中想要注入StringRedisTemplate但是我们使用的时候会发现,这个StringRedisTemplate对象时null。所以当我们需要有类似需求进行注入的时候要调整注入方式和写法,如下代码:ComponentpublicclassRedisHelper{privatestaticfinalLoggerloggerLoggerFactory。getLogger(RedisHelper。class);privatestaticStringRedisTemplateredisTemplate;AutowiredpublicvoidsetRedisTemplate(StringRedisTemplateredisTemplate){RedisHelper。redisTemplateredisTemplate;}scan实现parampattern表达式paramconsumer对迭代到的key进行操作publicstaticvoidscan(Stringpattern,Consumerbyte〔〕consumer){redisTemplate。execute((RedisConnectionconnection){try(Cursorbyte〔〕cursorconnection。scan(ScanOptions。scanOptions()。count(Long。MAXVALUE)。match(pattern)。build())){cursor。forEachRemaining(consumer);returnnull;}catch(IOExceptione){e。printStackTrace();thrownewRuntimeException(e);}});}获取符合条件的keyparampattern表达式returnpublicstaticListStringkeys(Stringpattern){ListStringkeysnewArrayList();scan(pattern,item{符合条件的keyStringkeynewString(item,StandardCharsets。UTF8);keys。add(key);});returnkeys;}publicstaticvoiddelete(ListStringlistKey){try{logger。info(需要删除key:listKey);Longdelete1redisTemplate。delete(listKey);logger。info(清除rediskey结果:{},delete1);}catch(Exceptione){e。printStackTrace();}}} 其修改的核心是: 首先加Component注解目的是让spring托管,另外注入StringRedisTemplate我们采用set方式进行注入即可。 作者:我是大明哥 链接:https:juejin。cnpost7011387262924095524