Alireza Fattahi Alireza Fattahi - 10 months ago 51
Java Question

Struts 2 and Spring how struts-created objects handled

We are using Struts 2 with spring frame work 4 ( I have some question about Struts bean creation.

When we use Struts with Spring we can easily use spring

, without annotating any of them as
). This seems that struts-created objects are spring managed beans.

This is not true, because when you look at
you can not find any action, validator or interceptor.

So if struts-created objects are not spring manage beans, why the spring annotations (
, ...) works quite well?

Is it technically possible that we create a new object (after spring start up) and pass it to Spring and let Spring setup it? How?!

Answer Source

Struts uses an ObjectFactory to build any object like actions, interceptors, validators, etc.:

ObjectFactory is responsible for building the core framework objects. Users may register their own implementation of the ObjectFactory to control instantiation of these Objects.

Struts-Spring plugin registers its own object factory StrutsSpringObjectFactory:

Struts object factory that integrates with Spring.

There, it overrides methods building Objects, such as buildBean().

Now if you look at the implementation, it is using method org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean()

which generally creates a new instance of the clazz argument.

Central method of this class: creates a bean instance, populates the bean instance, applies post-processors, etc.

Then, the newly created instance is passed for autowiring with org.springframework.beans.factory.config.AutowireCapableBeanFactory#autowireBeanProperties()

After that, this instance is passed to Guice for injection.

Now it's fully backed and ready to return.

Note that, if the bean is managed by Spring, it uses getBean method from application context, otherwise the new instance is created always by struts-spring plugin if the bean is not managed by Spring.