java - SpringAOP 与 AspectJ 的介绍

标签 java aspectj spring-aop

我是 SpringAOP 的新手。我想写一个简单的 Introductions 示例,但不能清楚地理解它是如何工作的。

在文档中我发现:

Introduction: declaring additional methods or fields on behalf of a type. Spring AOP allows you to introduce new interfaces (and a corresponding implementation) to any advised object. For example, you could use an introduction to make a bean implement an IsModified interface, to simplify caching. (An introduction is known as an inter-type declaration in the AspectJ community.)

我写了一个简单的例子: 我用一种方法编写简单的类

public class Test {
    public void test1(){
        System.out.println("Test1");
    }
}

然后我写接口(interface)和实现这个接口(interface)的类

public interface ITest2 {
    void test2();
}

public class Test2Impl implements ITest2{
    @Override
    public void test2() {
        System.out.println("Test2");
    }
}

最后是我的一面

@Aspect
public class AspectClass {

    @DeclareParents(
            value = "by.bulgak.test.Test+",
            defaultImpl = Test2Impl.class
    )
    public static ITest2 test2;
}

我的 spring 配置文件如下所示:

<aop:aspectj-autoproxy/>
<bean id="aspect" class="by.bulgak.aspect.AspectClass" />

所以我的问题是: 我怎么能这样呢。我需要在我的主课上写什么才能取得成功? 可能是我需要写一些其他的类。(我在其中阅读有关 SpringAOP 的书我找不到完整的例子)

更新

我的主要方法是这样的:

public static void main(String[] args) {
    ApplicationContext appContext = new ClassPathXmlApplicationContext("spring-configuration.xml");
    Test test = (Test) appContext.getBean("test");
    test.test1();
    ITest2 test2 = (ITest2) appContext.getBean("test");
    test2.test2();

}

当我执行我的应用程序时,出现此错误:

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy5 cannot be cast to by.bulgak.test.Test

在这一行:

Test test = (Test) appContext.getBean("test");

最佳答案

首先,您需要在配置文件中定义 bean Test:

<bean id="test" class="Test" />

然后在 main 中,从 ApplicationContext 获取这个 bean:

Test test1 = (Test) context.getBean("test");

现在,从test1 引用,您只能调用定义在Test bean 中的方法。要使用新引入的行为,您需要对包含该行为的接口(interface)的引用进行类型转换:

ITest2 test2 = (ITest2) context.getBean("test");

然后,您可以从这个引用中访问Test2的方法:

test2.test2();

这将调用在 @DeclareParents 注释的 defaultImpl 属性中指定的 bean 中定义的方法。

关于java - SpringAOP 与 AspectJ 的介绍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17176169/

相关文章:

java - 如何在 android 中以编程方式隐藏文件夹,并访问那里的文件。

java - 在后台运行 Gradle Java 项目

java - spring 应用程序如何在 war 之外保留属性文件

java - @Lookup 方法不适用于 spring mvc 4.1

java - AspectJ 编译器 DeclareMixin 错误

android - Android : pointcut call(* Activity. onCreate(..)) 中的 AspectJ 未挑选出 Activity.onCreate() 调用

java - 在 AspectJ 中禁用/避免建议执行

java - 在 Spring 中使用 AspectJ 捕获映射器方法内的 setter

java - Spring中是否为每个Bean都创建了一个代理?

java - 如何测试我的异步进程是否已正确提交?