1,比如想为bean:Student,引入一个自我描述的功能describe();
@Component //声明为bean public Student{ ... //类方法,成员域,构造器 }
2,声明一个接口,接口方法声明为这个想新增的describe方法,实现这个接口:
2.1,声明一个接口
public interface Proxy { public void describe(); }
2.2,实现这个接口
@Component //声明为一个bean public classs ProxyImpl { public void describe(){ ....//具体的方法体 } }
3,实现一个切面,为目标类(Student)注入代理接口:
@Aspect //声明为一个切面类 @Component //声明为一个bean public class Aop{ @DeclareParents(value="package.Student+",defaultImpl = ProxyImpl.class) Proxy proxy; }
3.1,注解@DeclareParents的value属性表示目标类,用完全限定的类名来表示,+ 号表示目标类及其子类型,defaultImpl 属性表示代理接口实现类:
3.2,Proxy proxy; 表示为目标类注入的接口
4,实现一个javaconfig,不用xml的方式:
@Configuration //声明这是一个配置类 @ComponentScan //组件扫描,类所在的包都会被扫描,将@Component注解的类加入Spring容器 @EnableAspectJAutoProxy public class Config { }
5,测试:
public class Test{ public static void main(String[] args) { AnnotationConfigApplicationContext ct= new AnnotationConfigApplicationContext(Config.class); //从Config类加载Spring应用上下文 //不想使用新加入的describe方法, Student st=(Student)ct.getBean("student"); st.getDes(); //想使用新加入的describe方法, Proxy proxy =(Proxy)st; proxy.describe(); }
注:想要使用新加入的功能,那么就将Student对象进行转型(因为已经为Student注入了代理接口)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)