Annotation handling in spring

From Null-pointer

Jump to: navigation, search

This basis of much of the design and implementation is taken from the ehcache annotations work.

Contents

Namespace handler

package null-pointer.memcached.config;
 
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
 
/**
 * @author Paul Kane
 * @since 16-Sep-2010
 */
public class AnnotationDrivenMemcachedNamespaceHandler extends NamespaceHandlerSupport {
 
    @Override
    public void init() {
        this.registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenMemcachedBeanDefinitionParser());
    }
}

BeanDefinitionParser

AnnotationDrivenMemcachedBeanDefinitionParser.java

MethodInterceptor

Static method matcher pointcut

package null-pointer.memcached;
 
import org.springframework.aop.support.StaticMethodMatcherPointcut;
 
import java.lang.reflect.Method;
 
 
public class CacheStaticMethodMatcherPointcut extends StaticMethodMatcherPointcut {
    private CacheManager cacheManager;
 
    public void setCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }
 
 
    @Override
    public boolean matches(Method method, Class targetClass) {
        return this.cacheManager.matches(method, targetClass);
    }
}

CacheManager

This is the bit that contains your business logic.

snippets:

/**
     * Can this CacheManager handled the method or target class provided
     * @param method
     * @param targetClass
     * @return
     */
    public boolean matches(Method method, Class<?> targetClass) {
        Cacheable cacheable = method.getAnnotation(Cacheable.class);
        TriggersRemove triggersRemove = method.getAnnotation(TriggersRemove.class);
 
        return (cacheable != null || triggersRemove != null);
    }
 
    /**
     * Get the method attribute based on the method and target class.
     * This handles @Cacheable and @TriggersRemove
     * @param method
     * @param targetClass
     * @return
     */
    public MethodAttribute getMethodAttribute(Method method, Class<?> targetClass) {
        try {
            createMap(targetClass);
 
            Cacheable cacheable = method.getAnnotation(Cacheable.class);
            if (cacheable != null) {
                return new CacheableAttribute(getCache(cacheable.cacheName()), cacheable);
            }
 
            TriggersRemove triggersRemove = method.getAnnotation(TriggersRemove.class);
            if (triggersRemove != null) {
                return new TriggersRemoveAttribute(getCaches(triggersRemove.cacheName()), triggersRemove);
            }
        }
        catch (Exception e) {
            logger.error("", e);
        }
 
        return null;
    }

See Also

References

Personal tools