Spring 框架破坏注入

问题描述 投票:0回答:1

谁能解释一下 Spring 中的这种行为?有一个抽象类:

abstract class BaseRepo {
    @Autowired
    protected lateinit var dsl: DSLContext
    // ....
}

@Repository
class MyRepo : BaseRepo {
    // ...
}

问题:为什么在

MyRepo
被声明为
@Repository
的情况下,框架不会初始化
@Autowired
字段 –
protected lateinit var dsl: DslContext
,但是如果将
@Repository
更改为
@Service
@Component
,注入作品?这很奇怪,因为
@Repository
@Component
的子类型,只是在规范级别,但事实证明不是,Spring 对它们的处理方式不同。

附注 我在 Spring Boot 3 上注意到了它,我还没有在 Spring Boot 2 上测试过它。构造函数注入 - 不建议

spring spring-boot kotlin
1个回答
0
投票

我认为在处理依赖注入时,

@Repository
的处理方式有所不同。我刚刚对此进行了测试,无需构造函数注入即可完成这项工作的唯一方法是使用 getter/setter:

import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseRepo {

    private DSLContext dsl;

    @Autowired
    protected void setDsl(final DSLContext dsl) {
        this.dsl = dsl;
    }

    protected DSLContext getDsl() {
        return dsl;
    }

}

这可能不是一个完整的答案,但也许它对您有帮助,因为它保留了封装并且不需要构造函数注入。

© www.soinside.com 2019 - 2024. All rights reserved.