简体   繁体   中英

Checking Redis @Configuration in SpringBoot

Is there a way to check if @Configuration components are being loaded when run a spring boot app ? I have some 'null pointer' problems when i use this app:

Main class

@ComponentScan(basePackages = "com.pack")
@EnableAutoConfiguration
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

Configuration class

package com.pack.config;
@Configuration
public class DataBaseConfig {

    @Bean
    JedisConnectionFactory jedisConnFactory() {    
        return new JedisConnectionFactory();
    }

    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        return stringRedisSerializer;
    }

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(jedisConnFactory());
        redisTemplate.setKeySerializer(stringRedisSerializer());
        return redisTemplate;
    }
}

And when i try to use RedisTemplate:

public class ServiceDummy  {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    public void save(String data){
        redisTemplate.opsForValue().set("1234", data);
    }

}

im getting a nullPointer.

As @Todd correctly pointed out, you can't expect Spring to manage beans that are not registered to Spring context.

So you need to:

  1. Mark that bean as Spring bean with @Component annotation, or in this case @Service annotation would be better.
  2. Make sure that ServiceDummy is under com.pack package, so that Spring can scan that component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM