Java 自动关联派生类是否也可以确保基类已设置?
3类<代码>测试类、基础类、派生类 在Java 自动关联派生类是否也可以确保基类已设置?,java,spring,spring-boot,autowired,spring-annotations,Java,Spring,Spring Boot,Autowired,Spring Annotations,3类测试类、基础类、派生类 在Base类中,我有几个字段(比如a和B),它们是自动连接的,也是一个构造函数 在派生的中,我有抽象方法的实现 当我在测试中自动连接派生的类时,基本类(A和B)的字段会被设置吗?是否将调用Base类的构造函数 Test() { @Autowired Derived derived; } @Component Base() { @Autowired A a; B b; public Base() { //Do Somethin
Base
类中,我有几个字段(比如a和B
),它们是自动连接的,也是一个构造函数
在派生的中,我有抽象方法的实现
当我在测试中自动连接派生的
类时,基本
类(A和B
)的字段会被设置吗?是否将调用Base
类的构造函数
Test() {
@Autowired
Derived derived;
}
@Component
Base() {
@Autowired
A a;
B b;
public Base() {
//Do Something
}
}
@Service
Derived() extends Base {
}
首先,我不是Spring IOC用户,我是guice IOC用户。所以如果你允许我对Spring做一些合理的假设,假设你的例子中只包含一些笔误
如果你有
class Base{
@Autowired A a;
@Autowired B b;
public Base(){
// doConfigurationOfOtherFields
}
}
@Service
class Derived extends Base{
//as per the language spec, if you don't include a constructor
//one is effectively auto-generated for you.
//and if you have a superclass it's param-free ctor will be called automatically
//meaning regardless of whether or not you typed this in source code
//effectively you get
Dervied(){
super();
}
}
Derived instance = iocContainer.resolve(Derived.class);
然后是的,a
和b
实例都应该由Spring创建和设置。而Base
的构造函数将被调用为(隐式)派生的构造函数执行的第一个操作
我不相信spring会在调用构造函数之前将赋值设置为a
和b
(除非它使用obgenisis),所以这些值会在调用构造函数之后赋值。是的,它会按照您的预期工作。你为什么不试试看呢?