使用spring引导数据redis模板获取空指针错误

5jvtdoz2  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(415)

配置:

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{

    @Bean(name = "template")
    public RedisTemplate<String, Object> template(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer<Object> jacksonSeial = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        StringRedisSerializer stringSerial = new StringRedisSerializer();
        template.setKeySerializer(stringSerial);
        template.setValueSerializer(jacksonSeial);
        template.setHashKeySerializer(stringSerial);
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }

}

用途:

@Autowired
    private RedisTemplate<String, Object> template;

还有这个

ValueOperations<String, Object> operations = template.opsForValue();

始终获取错误,警告堆栈跟踪为:

java.lang.NullPointerException: null
    at cn.com.agree.afa.jcomponent.CacheOperationImpl.<init>(CacheOperationImpl.java:15) ~[afa-interface-1.0.0.jar:na]
    at tc.bank.base.B_MemaryHandle.getCache(B_MemaryHandle.java:36) ~[afa-component-1.0.0.jar:na]
    at tc.bank.base.B_MemaryHandle.B_PutGlobalCache(B_MemaryHandle.java:64) ~[afa-component-1.0.0.jar:na]
    at tc.bank.base.B_LoadData.B_LoadErrorCodeConfig(B_LoadData.java:146) [afa-component-1.0.0.jar:na]
    at cn.com.agree.afa.trade.AimServer.BASE_startup.execute(BASE_startup.java:53) [main/:na]
    at cn.com.agree.trade.TradeManager.execute(TradeManager.java:43) [afa-interface-1.0.0.jar:na]
    at cn.com.agree.afa.App.run(App.java:71) [main/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) [spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:788) [spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) [spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1309) [spring-boot-2.4.0.jar:2.4.0]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1298) [spring-boot-2.4.0.jar:2.4.0]
    at cn.com.agree.afa.App.main(App.java:40) [main/:na]

我只想用springbootdateredis做一些crud操作,比如template<string,object>。请帮帮我

q8l4jmvw

q8l4jmvw1#

在构造函数完成之前,不能进行字段注入。将模板改为构造函数参数(通常避免字段注入)。

相关问题