我在初始化bean和将JPA存储库注入一个特定的bean时遇到了麻烦。不知道为什么它不起作用......
有一个interface
定义关键服务:
public interface KeyService {
Store getKeyStore();
Store getTrustStore();
}
实现此接口的和abstract
类:
public abstract class DefaultKeyService implements KeyService {
abstract KeyRecord loadKeyStore();
abstract KeyRecord loadTrustStore();
/* rest omitted... */
}
和扩展抽象类的基础class
:
@Service
public class DatabaseKeyService extends DefaultKeyService {
@Autowired
private KeyRecordRepository keyRecordRepository;
@Override
protected KeyRecord loadKeyStore() {
return extract(keyRecordRepository.findKeyStore());
}
@Override
protected KeyRecord loadTrustStore() {
return extract(keyRecordRepository.findTrustStore());
}
/* rest omitted... */
}
bean
初始化:
@Bean
public KeyService keyService() {
return new DatabaseKeyService();
}
这是一个KeyRecordRepository
存储库:
public interface KeyRecordRepository extends Repository<KeyRecord, Long> {
KeyRecord save(KeyRecord keyRecord);
@Query("SELECT t FROM KeyRecord t WHERE key_type = 'KEY_STORE' AND is_active = TRUE")
Iterable<KeyRecord> findKeyStore();
@Query("SELECT t FROM KeyRecord t WHERE key_type = 'TRUST_STORE' AND is_active = TRUE")
Iterable<KeyRecord> findTrustStore();
KeyRecord findById(long id);
}
问题:keyRecordRepository
类中的DatabaseKeyService
是否仍然为空?真的我不知道为什么只有这个字段不是注入。其他豆类和存储库工作得很好。
因为父类是抽象类而不是问题吗?
答案 0 :(得分:0)
必须使用@Component注释DatabaseKeyService才能成为Spring托管bean。
答案 1 :(得分:0)
您的问题与类DatabaseKeyService有2个bean有关。一个来自配置类 - @Bean注释,第二个来自@Service注释。
删除时可能
@Bean
public KeyService keyService() {
return new DatabaseKeyService();
}
使用@Service注入将起作用。
如果要使用@Bean,则必须添加KeyRecordRepository。我更喜欢使用构造函数注入,因此首先在DatabaseKeyService
中创建它public DatabaseKeyService(KeyRecordRepository keyRecordRepository) {
this.keyRecordRepository = keyRecordRepository;
}
然后在您的配置文件中
//other
@Autowired
private KeyRecordRepository keyRecordRepository;
@Bean
public KeyService keyService() {
return new DatabaseKeyService(keyRecordRepository);
}