工具類使用@Autowired無法注入bean的解決方法


配置文件增加掃描工具包類

<context:component-scan base-package="com.test.util" />

工具類需要使用@Component注解

package com.test.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RedisCache {
    @Autowired
    private RedisTemplate redisTemplate;

    public void setValue(Object key, Object value){
        redisTemplate.opsForValue().set(key, value);
    }

    public void setValue(Object key, Object value, long timeout, TimeUnit unit){
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public Object getValue(Object key){
        Object value = redisTemplate.opsForValue().get(key);
        return value;
    }
}
@Component注解的作用
把普通pojo類實例化到spring容器中,相當於配置文件中的 <bean id="" class=""/>
泛指各種組件,就是說當我們的類不屬於各種歸類的時候(不屬於@Controller、@Services等的時候),我們就可以使用@Component來標注這個類

使用時注入工具類

public class TestController {
    @Autowired
    private RedisCache rc;

    private String info(Map map, HttpServletRequest request){
        
        rc.setValue("name", "test");
        Object name = rc.getValue("name");
        Sysout.out.println(name);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM