Loading

Spring @Aspect进行类的接口扩展

Spring @Aspect进行类的接口扩展:

XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <!-- 这个声明会创建AnnotationAwareAspectJAutoProxyCreator,进行切面Bean的代理 -->
    <aop:aspectj-autoproxy />
    <!-- 必须将切面类声明为一个Bean -->
    <bean id="introduceAspect" class="com.stono.sprtest3.IntroduceAspect"></bean>
    <bean id="singer" class="com.stono.sprtest3.Singer"></bean>
</beans>

 

AppBean:

package com.stono.sprtest3;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppBeans13 {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("appbeans13.xml");
        // 有接口必须使用接口,使用Singer类会出现ClassCastException;
        Performer bean = (Performer) context.getBean("singer");
        IntroduceI introduceI = (IntroduceI) bean;
        introduceI.introduce();
    }
}

 

Aspect:

package com.stono.sprtest3;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
@Aspect
public class IntroduceAspect {
    // 为Performer接口扩展增加IntroduceI接口;
    @DeclareParents(value = "com.stono.sprtest3.Performer+", defaultImpl = DefaultIntro.class)
    public static IntroduceI introduceI;
}

 

POJO:

package com.stono.sprtest3;
public interface Performer {
    void perform();
}
package com.stono.sprtest3;
public class Singer implements Performer {
    public void perform() {
        System.out.println("com.stono.sprtest3.Singer.perform()");
    }
}
package com.stono.sprtest3;
public interface IntroduceI {
    void introduce();
}

package com.stono.sprtest3;
public class DefaultIntro implements IntroduceI {
    @Override
    public void introduce() {
        System.out.println("this is default introduce");
    }
}

 

posted @ 2015-10-08 11:34  stono  阅读(1523)  评论(0编辑  收藏  举报