Spring 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 运行此应用程序时,我得到

线程"main"中的异常 java.lang.NullPointerException at com.example.cache.impl.StorageServiceImpl.saveParameter(StorageServiceImpl.java:16( at com.example.cache.ApplicationConfiguration.main(ApplicationConfiguration.java:17(

不知道出了什么问题?

你不能在任何 bean 上使用 new,你需要@Autowire它。注释仅适用于每个级别的弹簧管理的 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;
  }
}

最新更新