【问题标题】:It there a "Spring way" to get an implementation from an annotated interface?是否有“Spring 方式”从带注释的接口获取实现?
【发布时间】:2012-11-20 15:12:04
【问题描述】:

我想废弃一些样板。假设我有一个带有自定义注释的自定义界面:

interface MyInterface {
    @DoSomething("crazy")
    public String aMethod(int numberOfJumps); 
}

现在我可以编写一个InvocationHandler,并生成一个Proxy 实现,它根据注释和方法参数或多或少有用,并返回适当的结果。这很好用。

我的问题是我是否可以使用 Spring 的某些机制来获得相同的结果,但可能更安全、更快、更灵活和/或更可配置。 Spring AOP 注释看起来很有前途,但它们似乎需要一个类,而不是一个接口。

[更新]

为了清楚我想要什么,我现在的代码大纲:

public interface TestInterface {
    @MyAnnotation(name = "foo")
    public void testMethod(String arg);
}

public class AnnotationProxy {
    @SuppressWarnings("unchecked")
    public static <T> T getImplementation(Class<T> annotatedInterface) {
       return (T) Proxy.newProxyInstance(annotatedInterface.getClassLoader(),
               new Class<?>[]{annotatedInterface},
               new AnnotationHandler());
    }

    private static class AnnotationHandler implements InvocationHandler {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("Args " + Arrays.toString(args));
            System.out.println("Annotations" + Arrays.toString(method.getAnnotations()));
            return "useful value";
        }
    }
}

TestInterface ti = getImplementation(TestInterface.class);
String s = ti.testMethod("xyz"); //"useful value"

如您所见,我凭空创建了一个对象(以及一些丑陋的反射材料)。我想知道我是否可以用一种更文明、更春天的方式来做到这一点。

【问题讨论】:

  • 不确定,但你可以使用 spring aop 的 xml 方法作为接口方法。
  • 我不确定使用带注释的接口是一种好习惯,例如在使用 CGLIB 代理时,我相信有关接口方法注释的信息将会消失。

标签: java spring interface annotations spring-aop


【解决方案1】:

一种方法是扫描具有您喜欢的注释的方法的接口,在 Spring 应用程序上下文中创建和注册代理。

示例

让我们有一个接口Test,我们要为其创建和注册代理:

package com.test;

public interface Test {
    @DoSomething(pattern = "[%s]")
    void print(String value);
}

我们的注解如下所示:

package com.test;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface DoSomething {

    String pattern();

}

我们希望在这样的应用程序中使用它:

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.test.Test;

public class Main {
    public static void main(final String[] args) throws Exception {
        final ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("test.xml");
        final Test test = ctx.getBean(Test.class);
        test.print("Hello");
    }
}

我们的 test.xml Spring 配置文件只包含对组件的扫描:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="com.test"/>
</beans>

不是重点。为了创建和注册代理,我们必须实现BeanFactoryPostProcessor 来扫描接口并创建代理:

package com.test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
import org.springframework.stereotype.Component;

@Component
public class DoSomethingPostprocessor implements BeanFactoryPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Object createDoSomethingBean(final MethodMetadata mmd, final Map<String, Object> attributes)
            throws Exception {
        final String pattern = (String) attributes.get("pattern");
        final Class<?> clazz = Class.forName(mmd.getDeclaringClassName());
        return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz },
                new InvocationHandler() {

                    @Override
                    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
                        System.out.println(String.format(pattern, args[0]));

                        return null;
                    }
                });
    }

    @Override
    public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
        try {
            final String packageSearchPath = "classpath*:com/**/*.class";

            final Resource[] resources =
                    applicationContext.getResources(packageSearchPath);
            final SimpleMetadataReaderFactory factory = new
                    SimpleMetadataReaderFactory(applicationContext);

            for (final Resource resource : resources) {
                final MetadataReader mdReader = factory.getMetadataReader(resource);

                final AnnotationMetadata am = mdReader.getAnnotationMetadata();
                final Set<MethodMetadata> methodMetadata =
                        am.getAnnotatedMethods(DoSomething.class.getName());
                for (final MethodMetadata mmd : methodMetadata) {
                    final Map<String, Object> attributes =
                            mmd.getAnnotationAttributes(DoSomething.class.getName());
                    final String beanName = mmd.getDeclaringClassName();
                    beanFactory.registerSingleton(beanName, createDoSomethingBean(mmd, attributes));
                }
            }
        } catch (final Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

【讨论】:

  • 非常感谢,这看起来很有前途!
【解决方案2】:

你可以使用Spring AOP来拦截和post处理注解的方法:

@Aspect
public class ProcessDoSomethingAspect {

    @AfterReturning(value = "execution(@annotation(doSomething) * *.*(..))", returning = "result")
    public String processResult(my.package.DoSomething doSomething, String result) {
        // process result here
        return result;
    }   

}

【讨论】:

  • 是的,我知道,但是我有一个接口,而不是一个类,那么我如何从中获得一个实现呢?
  • 你想访问截获的对象吗?
  • 不,我想创建一个新对象而不写一个类,只基于接口和AOP魔法左右
  • 你希望如何定义这个新类的行为?
  • 行为应该由AOP定义:它应该读取注解和方法参数,计算一个值并返回它。没有任何“真实”的方法。
猜你喜欢
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2014-08-08
  • 2011-12-21
  • 2010-10-19
相关资源
最近更新 更多