Struts 2 and Spring how struts-created objects han

2019-02-14 07:17发布

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?!

1条回答
趁早两清
2楼-- · 2019-02-14 07:42

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 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.

查看更多
登录 后发表回答