如何在Java 8中使用Spring Aspect保留方法参数名称

时间:2015-03-07 09:34:56

标签: java spring spring-aop

我已经完成了在Java 8中获取参数名称所需的内容。 当MyBean没有任何方面时,我会得到名字:'first'和'second'。

但是当设置方面时,bean被标记为MyBean $$ EnhancerBySpringCGLIB并且我拥有的是:'arg0''arg1'

该测试使用spring 4.1.5和aspectj 1.8.5进行。

我缺少什么?

package com.test;

public class MyBean {

    public void doSomething(String first, int second) {
        System.out.println("something");
    }
}


package com.test;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class MinimalAspect {
    @Around("execution(* com.test.MyBean.*(..))")
    public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Around before is running!");
        joinPoint.proceed();
        System.out.println("Around after is running!");
    }
}

package com.test;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) throws Exception {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-config.xml");
        MyBean myBean = (MyBean) appContext.getBean("myBean");
        for (Method method : myBean.getClass().getMethods()) {
            System.out.print(method.getName() + "(");
            for (Parameter parameter : method.getParameters()) {
                System.out.print(parameter.getType());
                System.out.print(' ');
                System.out.print(parameter.getName());
                System.out.print(' ');
            }
            System.out.println(")");
        }
    }
}


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd ">

    <aop:aspectj-autoproxy />
    <bean id="myBean" class="com.test.MyBean" />
    <!-- Aspect -->
    <bean id="minimalAspect" class="com.test.MinimalAspect" />
</beans>

1 个答案:

答案 0 :(得分:1)

Spring因为注释而增强了你的bean,所以myBean.getClass()返回一个包装类而不是你自己的类,它有通用的参数名。这应该返回原始类

MyBean myBean = (MyBean) appContext.getBean("myBean");
Class clazz = org.springframework.utils.ClassUtils.getUserClass(myBean.getClass());
for (Method method : clazz.getMethods()) {
...