Does autowiring a derived class also ensures the base class is setup?

时间:2015-07-28 23:16:37

标签: java spring spring-boot autowired spring-annotations

3 classes Test, Base, Derived

In the Base class I have a a few fields (say A and B) which are Autowired and also a constructor.

In the Derived I have the implementation of the abstract methods.

When I autowire the Derived class in Test will the fields of the Base class (A and B) be setup? Will the constructor of the Base class be called?

Test() {
   @Autowired
   Derived derived;
}

@Component
Base() {
  @Autowired 
  A a;
  B b;

  public Base() {
     //Do Something
  }
}

@Service
Derived() extends Base {

}

1 个答案:

答案 0 :(得分:0)

Firstly I'm not a Spring IOC user, I'm a guice IOC user. So if you'll allow me to make some reasonable assumptions about Spring, and assuming your example simply contains some clerical errors

If you had

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^staging.mydomain.com.au$
RewriteRule ^(.*)$ http://www.mydomain.com.au/portfolio [R=301,L]
</IfModule>

Then yes, both 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); and a instances should be created and set by Spring. and the constructor of b will be called as the first action taken by the (implicit) Base constructor.

I do not believe spring will set assign values to Derived and a before the constructor is called (unless its using obgenisis), so those values will be assigned after the constructor is called.