繁体   English   中英

没有在Spring Boot中扩展抽象类的类中注入bean

[英]Not injected bean in class that extends abstract class in Spring Boot

我在初始化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);
}

问题DatabaseKeyService类中的keyRecordRepository为何仍为null是否有某些原因? 我真的不知道为什么只有这一本场没有注入。 其他bean和存储库也可以正常工作。

因为父类是抽象类,不会有问题吗?

必须使用@Component注释DatabaseKeyService,以使其成为Spring托管的bean。

您的问题与为类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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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