本文中主要包含aspectj introduction demo。
例如下面的一个类Product:
/** * */ package aop.aspectj.introduction; /** * 这是一个测试类,主要是来测试不通过修改源代码的形式 * 来实现对这个类新增加一个功能. * @author jefferyxu * */ public class Product { private String productId; private String name; private String description; private int price; /** * @return the productId */ public String getProductId() { return productId; } /** * @param productId the productId to set */ public void setProductId(String productId) { this.productId = productId; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the price */ public int getPrice() { return price; } /** * @param price the price to set */ public void setPrice(int price) { this.price = price; } }
如果想要给这个类增加一个属性或者是方法的话,最简单方法就是修改代码,但是这么做不得不面临代码的重新测试,那么如何解决?答案之一就是使用aspectj的introduction性质。具体做法如下:
IValidatable.java :
/** * */ package aop.aspectj.introduction; /** * @author jefferyxu * */ public interface IValidatable { boolean isOnSale(); }
ProductValidatableAspect.java
/** * @author jefferyxu */ package aop.aspectj.introduction; public aspect ProductValidatableAspect { /** * 使用aspectj的特性,不改变product的源代码,而对这个 * 类新增加一个新的功能 */ declare parents: Product extends IValidatable; public boolean Product.isOnSale() { return this.getPrice() > 0 ? true : false; } }
客户端可以这么使用这个类了,就好像这个类中存在了一个方法isOnSale方法:
/** * */ package aop.aspectj.introduction; /** * @author jefferyxu * */ public class TestProduct { public static void main(String[] args) { Product product = new Product(); product.setPrice(10); System.out.println(((IValidatable)product).isOnSale()); } }