SpringでAOPの勉強
今日はProxyとcglibの原理について勉強しました.
準備作業は、cgligとproxy代理について勉強します.
1、cglibの学習、cglibは相続関係によって代理を実現する目的であり、具体的なコードは以下の通りである.
Springのコアモジュールは、beanとaopです.この中でbeanモジュールはaopに対してサポートを提供しています.
準備作業は、cgligとproxy代理について勉強します.
1、cglibの学習、cglibは相続関係によって代理を実現する目的であり、具体的なコードは以下の通りである.
public class AOPInstrumenter implements MethodInterceptor {
private static Log logger = LogFactory.getLog(AOPInstrumenter.class);
private Enhancer enhancer = new Enhancer();
public Object getInstrumentedClass(Class clz) {
enhancer.setSuperclass(clz);
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object o, Method method, Object[] methodParameters,MethodProxy methodProxy) throws Throwable {
logger.debug("Before Method =>" + method.getName());
Object result = methodProxy.invokeSuper(o, methodParameters);
logger.debug("After Method =>" + method.getName());
return result;
}
}
2、proxyエージェントは、主にインターフェースを実現することによって代理の目的を実現します.すなわち、具体的なコードは以下の通りです.public class AOPHandler implements InvocationHandler {
private static Log logger = LogFactory.getLog(AOPHandler.class);
private List interceptors = null;
private Object originalObject;
/**
*
*
* @param obj
* @return
*/
public Object bind(Object obj) {
this.originalObject = obj;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
}
/**
* Invoke , Interceptor,
* (before)、 (after) (exceptionThrow)
*/
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
Object result = null;
Throwable ex = null;
InvocationInfo invInfo = new InvocationInfo(proxy, method, args,result, ex);
logger.debug("Invoking Before Intercetpors!");
invokeInterceptorsBefore(invInfo);
try {
logger.debug("Invoking Proxy Method!");
result = method.invoke(originalObject, args);
invInfo.setResult(result);
logger.debug("Invoking After Method!");
invokeInterceptorsAfter(invInfo);
} catch (Throwable tr) {
invInfo.setException(tr);
logger.debug("Invoking exceptionThrow Method!");
invokeInterceptorsExceptionThrow(invInfo);
throw new AOPRuntimeException(tr);
}
return result;
}
/**
* Interceptor
*
* @return
*/
private synchronized List getIntercetors() {
if (null == interceptors) {
interceptors = new ArrayList();
//Todo: , Interceptor
interceptors.add(new MyInterceptor());
}
return interceptors;
}
/**
*
*
* @param invInfo
*/
private void invokeInterceptorsBefore(InvocationInfo invInfo) {
List interceptors = getIntercetors();
int len = interceptors.size();
for (int i = 0; i < len; i++) {
((Interceptor) interceptors.get(i)).before(invInfo);
}
}
/**
*
*
* @param invInfo
*/
private void invokeInterceptorsAfter(InvocationInfo invInfo) {
List interceptors = getIntercetors();
int len = interceptors.size();
for (int i = len - 1; i >= 0; i--) {
((Interceptor) interceptors.get(i)).after(invInfo);
}
}
/**
*
*
* @param invInfo
*/
private void invokeInterceptorsExceptionThrow(InvocationInfo invInfo) {
List interceptors = getIntercetors();
int len = interceptors.size();
for (int i = len - 1; i >= 0; i--) {
((Interceptor) interceptors.get(i)).exceptionThrow(invInfo);
}
}
}
public class AOPFactory {
static AOPHandler txHandler ;
private static Log logger = LogFactory.getLog(AOPFactory.class);
/**
*
*
* @param clzName
* @return
* @throws ClassNotFoundException
*/
public static Object getClassInstance(String clzName) {
Class cls;
try {
cls = Class.forName(clzName);
return (Object) cls.newInstance();
} catch (ClassNotFoundException e) {
logger.debug(e);
throw new AOPRuntimeException(e);
} catch (InstantiationException e) {
logger.debug(e);
throw new AOPRuntimeException(e);
} catch (IllegalAccessException e) {
logger.debug(e);
throw new AOPRuntimeException(e);
}
}
/**
* , AOP
*
* @param clzName
* @return
*/
public static Object getAOPProxyedObject(String clzName) {
txHandler = new AOPHandler();
Object obj = getClassInstance(clzName);
return txHandler.bind(obj);
}
/**
* @return Returns the txHandler.
*/
public static AOPHandler getTxHandler() {
return txHandler;
}
}
public interface Interceptor {
public void before(InvocationInfo invInfo);
public void after(InvocationInfo invInfo);
public void exceptionThrow(InvocationInfo invInfo);
}
public class MyInterceptor implements Interceptor {
private static Log logger = LogFactory.getLog(MyInterceptor.class);
public void before(InvocationInfo invInfo) {
logger.debug("Pre-processing");
}
public void after(InvocationInfo invInfo) {
logger.debug("Post-processing");
}
public void exceptionThrow(InvocationInfo invInfo) {
logger.debug("Exception-processing");
}
}
3、SpringにおけるAOPの実現.Springの中のcgligとproxyを分析します.Springのコアモジュールは、beanとaopです.この中でbeanモジュールはaopに対してサポートを提供しています.
public abstract class AbstractBeanFactory implements ConfigurableBeanFactory {
public Object getBean(String name, Class requiredType, Object[] args) throws BeansException {
String beanName = transformedBeanName(name);
Object bean = null;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = null;
synchronized (this.singletonCache) {
sharedInstance = this.singletonCache.get(beanName);
}
if (sharedInstance != null) {
if (sharedInstance == CURRENTLY_IN_CREATION) {
throw new BeanCurrentlyInCreationException(beanName);
}
if (logger.isDebugEnabled()) {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
bean = getObjectForSharedInstance(name, sharedInstance); }
else {
// Check if bean definition exists in this factory.
RootBeanDefinition mergedBeanDefinition = null;
try {
mergedBeanDefinition = getMergedBeanDefinition(beanName, false);
}
catch (NoSuchBeanDefinitionException ex) {
// Not found -> check parent.
if (this.parentBeanFactory instanceof AbstractBeanFactory) {
// Delegation to parent with args only possible for AbstractBeanFactory.
return ((AbstractBeanFactory) this.parentBeanFactory).getBean(name, requiredType, args);
}
else if (this.parentBeanFactory != null && args == null) {
// No args -> delegate to standard getBean method.
return this.parentBeanFactory.getBean(name, requiredType);
}
throw ex;
}
checkMergedBeanDefinition(mergedBeanDefinition, beanName, requiredType, args);
// Create bean instance.
if (mergedBeanDefinition.isSingleton()) {
synchronized (this.singletonCache) {
// re-check singleton cache within synchronized block
sharedInstance = this.singletonCache.get(beanName);
if (sharedInstance == null) {
if (logger.isInfoEnabled()) {
logger.info("Creating shared instance of singleton bean '" + beanName + "'");
}
this.singletonCache.put(beanName, CURRENTLY_IN_CREATION);
try {
sharedInstance = createBean(beanName, mergedBeanDefinition, args);
this.singletonCache.put(beanName, sharedInstance);
}
catch (BeansException ex) {
this.singletonCache.remove(beanName);
throw ex;
}
}
}
bean = getObjectForSharedInstance(name, sharedInstance);
}
else {
// It's a prototype -> create a new instance.
bean = createBean(name, mergedBeanDefinition, args);
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return bean;
}
}
public abstract class AbstractBeanFactory implements ConfigurableBeanFactory {
protected Object getObjectForSharedInstance(String name, Object beanInstance) throws BeansException {
String beanName = transformedBeanName(name);
// Don't let calling code try to dereference the
// bean factory if the bean isn't a factory.
if (isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (beanInstance instanceof FactoryBean) {
if (!isFactoryDereference(name)) {
// Return bean instance from factory.
FactoryBean factory = (FactoryBean) beanInstance;
if (logger.isDebugEnabled()) {
logger.debug("Bean with name '" + beanName + "' is a factory bean");
}
try {
beanInstance = factory.getObject();
}
catch (Exception ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
if (beanInstance == null) {
throw new FactoryBeanNotInitializedException(
beanName, "FactoryBean returned null object: " +
"probably not fully initialized (maybe due to circular bean reference)");
}
}
else {
// The user wants the factory itself.
if (logger.isDebugEnabled()) {
logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");
}
}
}
return beanInstance;
}
}
public class ProxyFactoryBean extends AdvisedSupport
implements FactoryBean, BeanFactoryAware, AdvisedSupportListener {
public Object getObject() throws BeansException {
return this.singleton ? getSingletonInstance() : newPrototypeInstance();
}
private Object getSingletonInstance() {
if (this.singletonInstance == null) {
super.setFrozen(this.freezeProxy);
this.singletonInstance = createAopProxy().getProxy();
}
return this.singletonInstance;
}
}
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
Class targetClass = this.advised.getTargetSource().getTargetClass();
logger.debug("Creating JDK dynamic proxy" +
(targetClass != null ? " for [" + targetClass.getName() + "]" : ""));
}
Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}
}
public class Cglib2AopProxy implements AopProxy, Serializable {
public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
Class targetClass = this.advised.getTargetSource().getTargetClass();
logger.debug("Creating CGLIB2 proxy" +
(targetClass != null ? " for [" + targetClass.getName() + "]" : ""));
}
Enhancer enhancer = new Enhancer();
try {
Class rootClass = this.advised.getTargetSource().getTargetClass();
if (AopUtils.isCglibProxyClass(rootClass)) {
enhancer.setSuperclass(rootClass.getSuperclass());
}
else {
enhancer.setSuperclass(rootClass);
}
enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised));
enhancer.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class));
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
Callback[] callbacks = getCallbacks(rootClass);
enhancer.setCallbacks(callbacks);
if(CglibUtils.canSkipConstructorInterception()) {
enhancer.setInterceptDuringConstruction(false);
}
Class[] types = new Class[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
enhancer.setCallbackTypes(types);
// generate the proxy class and create a proxy instance
Object proxy;
if (this.constructorArgs != null) {
proxy = enhancer.create(this.constructorArgTypes, this.constructorArgs);
}
else {
proxy = enhancer.create();
}
return proxy;
}
catch (CodeGenerationException ex) {
throw new AspectException("Couldn't generate CGLIB subclass of class '" +
this.advised.getTargetSource().getTargetClass() + "': " +
"Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (IllegalArgumentException ex) {
throw new AspectException("Couldn't generate CGLIB subclass of class '" +
this.advised.getTargetSource().getTargetClass() + "': " +
"Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Exception ex) {
// TargetSource.getTarget failed
throw new AspectException("Unexpected AOP exception", ex);
}
}
}