`
jinnianshilongnian
  • 浏览: 21436581 次
  • 性别: Icon_minigender_1
博客专栏
5c8dac6a-21dc-3466-8abb-057664ab39c7
跟我学spring3
浏览量:2405437
D659df3e-4ad7-3b12-8b9a-1e94abd75ac3
Spring杂谈
浏览量:2998016
43989fe4-8b6b-3109-aaec-379d27dd4090
跟开涛学SpringMVC...
浏览量:5631699
1df97887-a9e1-3328-b6da-091f51f886a1
Servlet3.1规范翻...
浏览量:257622
4f347843-a078-36c1-977f-797c7fc123fc
springmvc杂谈
浏览量:1593292
22722232-95c1-34f2-b8e1-d059493d3d98
hibernate杂谈
浏览量:249006
45b32b6f-7468-3077-be40-00a5853c9a48
跟我学Shiro
浏览量:5847847
Group-logo
跟我学Nginx+Lua开...
浏览量:698249
5041f67a-12b2-30ba-814d-b55f466529d5
亿级流量网站架构核心技术
浏览量:780592
社区版块
存档分类
最新评论

struts2+spring集成bug——使用AOP时可能遇到的问题分析

阅读更多

之前一朋友问我strut2和spring集成时使用aop后造成注入失败:关于struts2-spring整合的问题,我就分析一下struts2如果和spring集成的,并解决这个问题。

 

此问题已经提交到struts2的JIRA,2.3.16将修复;https://issues.apache.org/jira/browse/WW-4110

 

问题:

但是当我对action类加了spring-aop之后,写@resource不加getset方法的情况下又报错了,好像spring的注解又失效了,不知道这是为什么,请问您碰到过这种情况吗。

 

默认情况下,失败的情况只有两种:

当如<action name="myAction" class="cn.javass.MyAction">时,即没有交给spring管理:

1、 @Autowired   private Resource resource; 但无setter方法;

2、有setter方法,如setResource(),但无名字为resource的bean。

 

分析

首先介绍下struts2怎么去和spring集成的。

1、如果需要和spring集成,需要添加struts2-spring-plugin-***.jar,此处我们使用struts2-spring-plugin-2.3.1.1.jar;

 

2、接着struts2在启动时会按照如下顺序加载配置文件:

struts-default.xml 默认配置

struts-plugin.xml  插件配置(可以多个)

struts.xml 我们自己的

 

3、自动注册StrutsSpringObjectFactory为struts2的ObjectFactory,因此拿struts2的组件等都是问它要;

 

    <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring" class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
    
    <!--  Make the Spring object factory the automatic default -->
    <constant name="struts.objectFactory" value="spring" />

 

4、 StrutsSpringObjectFactory继承了com.opensymphony.xwork2.spring.SpringObjectFactory,主要做了几件事情:

4.1、获取ApplicationContext:servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

4.2、获取自动装配的机制,可以在struts.xml配置常量:struts.objectFactory.spring.autoWire,默认是name;这个可以参考http://jinnianshilongnian.iteye.com/blog/1415461,3.3.3 自动装配;

 

5、接下来如果要获取如action,需要:

 

    @Override
    public Object buildBean(String beanName, Map<String, Object> extraContext, boolean injectInternal) throws Exception {
        Object o;
        
        if (appContext.containsBean(beanName)) {
            o = appContext.getBean(beanName);
        } else {
            Class beanClazz = getClassInstance(beanName);
            o = buildBean(beanClazz, extraContext);
        }
        if (injectInternal) {
            injectInternalBeans(o);
        }
        return o;
    }

5.1、首先查找spring容器有木有,如果有直接返回;

 

5.2、否则调用buildBean(beanClazz, extraContext);创建新的bean;即<action name="myAction" class="cn.javass.MyAction"> class配置的不是beanName时;

 

6、buildBean(beanClazz, extraContext);

 

    @Override
    public Object buildBean(Class clazz, Map<String, Object> extraContext) throws Exception {
        Object bean;

        try {
            // Decide to follow autowire strategy or use the legacy approach which mixes injection strategies
            if (alwaysRespectAutowireStrategy) {
                // Leave the creation up to Spring
                bean = autoWiringFactory.createBean(clazz, autowireStrategy, false);
                injectApplicationContext(bean);
                return injectInternalBeans(bean);
            } else {
                bean = autoWiringFactory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);
                bean = autoWiringFactory.applyBeanPostProcessorsBeforeInitialization(bean, bean.getClass().getName());
                // We don't need to call the init-method since one won't be registered.
                bean = autoWiringFactory.applyBeanPostProcessorsAfterInitialization(bean, bean.getClass().getName());
                return autoWireBean(bean, autoWiringFactory);
            }
        } catch (UnsatisfiedDependencyException e) {
            if (LOG.isErrorEnabled())
                LOG.error("Error building bean", e);
            // Fall back
            return autoWireBean(super.buildBean(clazz, extraContext), autoWiringFactory);
        }
    }

6.1、 如果是alwaysRespectAutowireStrategy,默认false,这个对于大家来说直接忽略,遗留策略,现在可以直接忽略。

6.2、正常情况会走到else中:

6.2.1、首先通过bean = autoWiringFactory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false)创建Bean;

6.2.2、执行Bean预处理:bean = autoWiringFactory.applyBeanPostProcessorsBeforeInitialization(bean, bean.getClass().getName()),此时可能发生@PostConstruct的初始化及一些Aware接口的注入;

6.2.2、执行Bean的后处理:bean = autoWiringFactory.applyBeanPostProcessorsAfterInitialization(bean, bean.getClass().getName()),此时可能发生创建代理对象;

6.2.3、最后调用autoWireBean(bean, autoWiringFactory)装配对象,此时会调用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory的populateBean完成,完成1、如果支持自动装配,会执行自动专配;2、如果有支持@Autowired注解,那么会调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues;

 

如上的流程可以参考如下文章,有详细讲解:

Spring开闭原则的表现-BeanPostProcessor的扩展点-1

Spring开闭原则的表现-BeanPostProcessor扩展点-2 

 

 

 

但是getBean的流程是(org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory):

 

1、InstantiationAwareBeanPostProcessor.applyBeanPostProcessorsBeforeInstantiation

2、InstantiationAwareBeanPostProcessor.applyBeanPostProcessorsAfterInitialization

如果此时有bean返回 直接返回;

3、doCreateBean

3.1、createBeanInstance

3.2、populateBean

3.2.1、InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation

3.2.2、autowire, for example AUTOWIRE_BY_NAME,AUTOWIRE_BY_TYPE

3.2.3、InstantiationAwareBeanPostProcessor.postProcessPropertyValues

3.2.4、applyPropertyValues

 

4、initializeBean

4.1、invokeAwareMethods

4.2、BeanPostProcessor.postProcessBeforeInitialization

4.3、invokeInitMethods

4.4、BeanPostProcessor.postProcessAfterInitialization

 

所以综上,SpringObjectFactory的实现是存在问题的,我给了一个正确的方式:

//1、instantiation
bean = autoWiringFactory.createBean(clazz, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, false);

//2、autowire
bean = autoWireBean(bean, autoWiringFactory);

//3、initialization
bean = autoWiringFactory.initializeBean(bean, bean.getClass().getName());

这才是正确的步骤。

 

如果按照struts2默认的实现,

bean = autoWiringFactory.applyBeanPostProcessorsAfterInitialization(bean, bean.getClass().getName());会执行创建代理,那么bean此时是代理对象;

 

那么接下来autoWireBean(bean, autoWiringFactory);会造成@Autowired   private Resource resource; 但无setter方法;注入失败。

 

到此分析完毕,已经提交struts2 jira:

https://issues.apache.org/jira/browse/WW-4110 

 

正确的SpringObjectFactory在附件中,请下载测试

3
3
分享到:
评论
8 楼 LinApex 2013-07-21  
jinnianshilongnian 写道
LinApex 写道
    <bean id="aspect" class="com.temp.common.advice.DaoMethodTimeAdvice"/>
    <aop:config>
        <aop:aspect ref="aspect">
            <aop:before method="before" pointcut="execution(* com.temp.web.action.*(..))"/>
        </aop:aspect>
    </aop:config>


1、详细的错误
2、配置文件
3、相关代码


没有错误,只是到 拦截  invocation.proceed(); 就出卡死,然后前台就跳转到一个空白页面... 这个比较神奇,我已经取消了 Action 层拦截了。。。下次再研究吧
7 楼 jinnianshilongnian 2013-07-21  
LinApex 写道
    <bean id="aspect" class="com.temp.common.advice.DaoMethodTimeAdvice"/>
    <aop:config>
        <aop:aspect ref="aspect">
            <aop:before method="before" pointcut="execution(* com.temp.web.action.*(..))"/>
        </aop:aspect>
    </aop:config>


1、详细的错误
2、配置文件
3、相关代码

6 楼 LinApex 2013-07-20  
    <bean id="aspect" class="com.temp.common.advice.DaoMethodTimeAdvice"/>
    <aop:config>
        <aop:aspect ref="aspect">
            <aop:before method="before" pointcut="execution(* com.temp.web.action.*(..))"/>
        </aop:aspect>
    </aop:config>
5 楼 LinApex 2013-07-20  
jinnianshilongnian 写道
LinApex 写道
Spring3.1.1 集成 Struts2 2.3.14.3 .
Spring 配置了以一个 拦截 struts2 Action 的 aop类,这个aop的拦截类的主要功能就是检查这个action的时间... 但是在请求 action 的时候,在aop这里就卡死了.. 然后报错。。不知道啥原因。

aop代码贴下 我先看看


aop 拦截器的代码:

package com.temp.common.advice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component(value = "ActionMethodTimeAdvice")
public final class ActionMethodTimeAdvice implements MethodInterceptor
{

private Logger logger = Logger.getLogger(this.getClass());

@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
StopWatch clock = new StopWatch();
clock.start();

Object result = invocation.proceed();

clock.stop();

// 方法参数类型,转换成简单类型
Class[] params = invocation.getMethod().getParameterTypes();
String[] simpleParams = new String[params.length];
for (int i = 0; i < params.length; i++)
{
simpleParams[i] = params[i].getSimpleName();
}
Object[] args = invocation.getArguments();

logger.info("Action execute Time:" + clock.getTime() + " ms [" + invocation.getThis().getClass().getName() + "." + invocation.getMethod().getName() + "(" + StringUtils.join(simpleParams, ",") + ")(" + StringUtils.join(args, ",") + ")] ");
return result;
}

}


Spring配置文件中的代码,与Dao层配置事务一样.对所有方法进行拦截.

4 楼 jinnianshilongnian 2013-06-22  
LinApex 写道
Spring3.1.1 集成 Struts2 2.3.14.3 .
Spring 配置了以一个 拦截 struts2 Action 的 aop类,这个aop的拦截类的主要功能就是检查这个action的时间... 但是在请求 action 的时候,在aop这里就卡死了.. 然后报错。。不知道啥原因。

aop代码贴下 我先看看
3 楼 LinApex 2013-06-22  
Spring3.1.1 集成 Struts2 2.3.14.3 .
Spring 配置了以一个 拦截 struts2 Action 的 aop类,这个aop的拦截类的主要功能就是检查这个action的时间... 但是在请求 action 的时候,在aop这里就卡死了.. 然后报错。。不知道啥原因。
2 楼 jinnianshilongnian 2013-06-20  
loveExtJs 写道
精彩!学习了,下来后再细读。

1 楼 loveExtJs 2013-06-20  
精彩!学习了,下来后再细读。

相关推荐

Global site tag (gtag.js) - Google Analytics