【问题标题】:Not injected bean in class that extends abstract class in Spring Boot未在 Spring Boot 中扩展抽象类的类中注入 bean
【发布时间】:2017-01-05 12:57:31
【问题描述】:

我在初始化 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 仍然为空?真的我不知道为什么只有这个字段没有注入。其他 bean 和存储库运行良好。

不会因为父类是抽象类而产生问题吗?

【问题讨论】:

  • 用@Component注释KeyRecordRepository的实现
  • KeyRecordRepository 没有实现。

标签: java spring


【解决方案1】:

DatabaseKeyService 必须使用 @Component 注释才能成为 Spring 托管 bean。

【讨论】:

  • 我有一个注释@Service - 忘了提,添加了。
  • 你的 Spring Boot 主类中有 @EnableAutoConfiguration 吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多