We are using Struts 2 with spring frame work 4 (https://struts.apache.org/docs/spring-plugin.html). I have some question about Struts bean creation.
When we use Struts with Spring we can easily use spring @Inject
, @Value
, @Resource
in Actions
, Validators
and Interceptors
, without annotating any of them as @Component
(or @Named
). This seems that struts-created objects are spring managed beans.
This is not true, because when you look at applicationContext.getBeanDefinitionNames()
you can not find any action, validator or interceptor.
So if Struts-created objects are not spring manage beans, why the spring annotations ( @Inject
, @Value
, ...) 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?!
Struts uses an
ObjectFactory
to build any object like actions, interceptors, validators, etc.:Struts-Spring plugin registers its own object factory
StrutsSpringObjectFactory
: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.
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 baked 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.