Spring Redis无法自动连线存储库

时间:2019-07-20 23:08:11

标签: spring-data-redis

我正在使用自定义Crudrespository将数据持久保存在Redis中。但是,我无法自动连接自定义存储库。

所有配置似乎正确,redis正在我的本地计算机上运行。

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CustomRepository extends CrudRepository<String, 
Long> {

String get(String key);

void put(String key, String value);
}

//////////

public class StorageServiceImpl implements IStorageService {


    @Autowired
    private CustomRepository respository;

    @Override
    public void saveParameter() {
    this.respository.put("key1","value1");
    }

    @Override
    public String getParameter() {
    return this.respository.get("key1");
    }

/////

@Service
public interface IStorageService {

    void saveParameter();

    String getParameter();
}
///////

@SpringBootApplication(scanBasePackages = {"com.example.cache"})
@EnableRedisRepositories(basePackages = {"com.example.cache.repository"})
public class ApplicationConfiguration {

public static void main(String[] args){
    SpringApplication.run(ApplicationConfiguration.class, args);
    new StorageServiceImpl().saveParameter();
        System.out.println(new StorageServiceImpl().getParameter());
    }
}

当我尝试使用gradle bootRun运行此应用程序时,我得到

线程“主”中的异常java.lang.NullPointerException         在com.example.cache.impl.StorageServiceImpl.saveParameter(StorageServiceImpl.java:16)         在com.example.cache.ApplicationConfiguration.main(ApplicationConfiguration.java:17)

不确定出什么事了吗

1 个答案:

答案 0 :(得分:2)

您不能在任何bean上使用new,而需要@Autowire。注释仅适用于每个级别的Spring托管Bean。

添加一个具有存储服务和创建方法的新bean的调用。

此外,我不记得在只有一个实现的情况下,spring-boot是否创建了bean,但是我相信您的StorageServiceImpl需要@Service注释,而不是接口。

从您的ApplicationConfiguration类中删除它。

new StorageServiceImpl().saveParameter();
System.out.println(new StorageServiceImpl().getParameter());

然后添加这个新类。

@Service
public class Startup {

    @Autowired
    IStorageService storageService;

    @PostConstruct
    public void init(){

         storageService.saveParameter();
         System.out.println(storageService().getParameter());
    }
}

您需要一个配置

@Configuration
@EnableRedisRepositories
public class ApplicationConfig {

  @Bean
  public RedisConnectionFactory connectionFactory() {
    return new JedisConnectionFactory();
  }

  @Bean
  public RedisTemplate<?, ?> redisTemplate() {

    RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
    return template;
  }
}