использование шаблона redis данных spring boot выдает ошибку нулевого указателя

#java #spring #spring-boot

#java #spring #spring-boot

Вопрос:

конфигурация:

 @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]
 

Я просто хочу использовать redis даты весенней загрузки для выполнения некоторых операций CRUD, таких как template<String, Object> .
пожалуйста, помогите мне

Комментарии:

1. Вызов метода ‘opsForValue’ приведет к ‘NullPointerException’

Ответ №1:

Внедрение поля не может произойти до тех пор, пока конструктор не будет завершен. Вместо этого сделайте шаблон параметром конструктора (и вообще избегайте ввода поля).

Комментарии:

1. Я едва могу вас понять, честно говоря, я впервые использую материалы, связанные с spring, не могли бы вы показать мне, как это исправить?

2. @Django47 Сделайте шаблон параметром в конструкторе вашего класса, как вы бы сделали, если бы у вас изначально не было Spring. (И приобретите привычку никогда не использовать @Autowired поля on, потому что это приводит к подобным проблемам; просто передайте все, что вам нужно, в конструкторе.)

3. Я изменил свой код на private ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(RedisConfig.class); @SuppressWarnings("unchecked") private RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>) ctx.getBean("redisTemplate"); private ValueOperations<String, Object> operations = redisTemplate.opsForValue(); и получил новую ошибку No CacheResolver specified, and no bean of type CacheManager found. Register a CacheManager bean or remove the @EnableCaching annotation from your configuration.

4. после удаления @EnableCaching программа, наконец, запускается без ошибок! но мне все еще нужно знать, как код получает метрики yml или properties

5. фанатичное использование @Value(«${spring …}») сработало для меня…

Ответ №2:

Добавление к ответу chrylis здесь.

Используйте lombok @RequiredArgsConstructor поверх вашего @Component класса. Он сгенерирует конструктор с требуемыми полями. Шаблон Redis будет инициализирован, и ошибка null исчезнет.

Комментарии:

1. Да, Lombok может помочь здесь, но у нас нет информации о зависимостях Lombok в проекте.