配置文件增加扫描工具包类
<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);
}
}