ROP的服务类经过@ServiceMethodBean进行注解,服务方法经过@ServiceMethod标注,ROP在启动时自动扫描Spring容器中的Bean,将服务方法写到服务注册表中.
最近发现了一个问题,是因为Java泛型的桥方法和合成方法引发的,下面举例说明:
java
package com.rop.session; ide
/** ui
* 其中T是登陆请求的类,而R是注销请求的类 spa
* @author : chenxh debug
* @date: 13-10-16 blog
*/ 图片
import com.rop.RopRequest; get
import org.slf4j.Logger; it
import org.slf4j.LoggerFactory;
import java.util.UUID;
public abstract class AuthenticationService<T extends RopRequest,R extends RopRequest> {
...
public abstract Object logon(T logonRequest);
/**
* 该方法在子类在实现,并打上@ServiceMethod注解,做为注销的服务方法
* @param loginRequest
* @return
*/
public abstract Object logout(R logoutRequest);
}
AuthenticationService定义了两个抽象方法,须要子类实现,以便实现登陆认证.
子类实现以下:
@ServiceMethodBean
public class AppAuthenticationService extends AuthenticationService<LogonRequest,LogoutRequest> {
public static final String USER_LOGON = "user.logon";
public static final String USER_LOGOUT = "user.logout";
...
@ServiceMethod(method = USER_LOGON, version = "1.0",
needInSession = NeedInSessionType.NO,ignoreSign = IgnoreSignType.YES)
@Override
public Object logon(LogonRequest logonRequest) {
...
}
@ServiceMethod(method = USER_LOGOUT, version = "1.0")
@Override
public Object logout(LogoutRequest logoutRequest) {
...
}
}
AppAuthenticationService类中覆盖了抽象父类中的方法,而且对泛型进行了具化.
可是当ROP扫描服务方法时,服务方法的入参识别发生了错误,错将入参识别为RopRequest,而非
LogonRequest,LogoutRequest.
断点跟踪到注册服务方法时,发现AuthenticationService类竟然有2个logon和2个logout方法:
1.logon(LogonRequest r)
2.logout(LogoutRequest r)
3.logon(RopRequest r)
4.logout(RopRequest r)
其中前两个方法是AuthenticationService中定义的方法,然后两个方法是为了实现泛型具化JAVA自动生产的方法,称为桥方法,可参见这篇文章的说明:
http://jiangshuiy.iteye.com/blog/1339105
后两个方法也有和前两个方法同样的@ServiceMethod注解,所以在ROP扫描时,就能够扫描到桥方法,而把真正的方法覆盖了.
JAVA的Method反射类中拥有判断是不是桥方法的方法:
Method#isBridge()
前两个方法返回的是false,然后两个方法返回的是true.
另外,桥方法也是合成方法(Synthetic),Method反射类中拥有判断是不是桥方法的方法:
Method#isSynthetic()
关于合成方法,亦请参考http://jiangshuiy.iteye.com/blog/1339105
为了不ROP扫描到这些杂攻杂八的方法,所以ROP扫描程序作了如下的调整:
private void registerFromContext(final ApplicationContext context) throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("对Spring上下文中的Bean进行扫描,查找ROP服务方法: " + context);
}
String[] beanNames = context.getBeanNamesForType(Object.class);
for (final String beanName : beanNames) {
Class<?> handlerType = context.getType(beanName);
//1只对标注 ServiceMethodBean的Bean进行扫描
if(AnnotationUtils.findAnnotation(handlerType,ServiceMethodBean.class) != null){
ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() {
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(method);
... }
},
new ReflectionUtils.MethodFilter() {
public boolean matches(Method method) {
//2不是合成方法,且标注了ServiceMethod的方法!!
return !method.isSynthetic() && AnnotationUtils.findAnnotation(method, ServiceMethod.class) != null;
}
}
);
}
}
...
}