2013-06-18 51 views
3

我是SpringAOP的新手。我想写一个简单的例子介绍,但不能清楚地知道它是如何工作的。SpringAOP引入AspectJ

在文档我发现:

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"); 
    } 
} 

然后我写的接口和类实现此接口

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我无法找到完整的例子)

UPDATE

我的主要方法是这样的:

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"); 
+0

让我看看你的配置文件中的'Test' bean声明。 –

+0

@RohitJain'' –

+0

@RohitJain但项目工作正常II评论这两行:'Test test =(Test)appContext.getBean(”test“); test.test1();' –

回答

3

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

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

然后在主,让这个bean从ApplicationContext

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

现在,从test1参考,您只能调用Test bean中定义的方法。要使用新引进的行为,就需要强制转换引用到包含行为的界面:

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

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

test2.test2(); 

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

+0

当我启动应用程序时,错误:线程中的异常“main”java.lang.ClassCastException:com.sun.proxy。$ Proxy5无法转换为by.bulgak.test.Test' –

+0

你在哪里得到这个异常? –