先定义一个需要被introduce的interface
再写这个interface的mixin
最后是怎么使用这个mixin
java 代码
- public interface EditAware {
- public Object getOldValue(String propertyName);
- public boolean isEdited(String propertyName);
- }
java 代码
- import org.aopalliance.intercept.MethodInvocation;
- import org.apache.commons.beanutils.PropertyUtils;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.aop.support.DelegatingIntroductionInterceptor;
- public class EditAwareMixin extends DelegatingIntroductionInterceptor implements
- EditAware {
- private transient Map map = new HashMap();
- public Object getOldValue(String propertyName) {
- return map.get(propertyName);
- }
- public boolean isEdited(String propertyName) {
- return map.containsKey(propertyName);
- }
- public Object invoke(MethodInvocation invocation) throws Throwable {
- if (invocation.getMethod().getName().indexOf("set") == 0) {
- Object _this = invocation.getThis();
- String propertyName = invocation.getMethod().getName().substring(3);
- propertyName = StringUtils.uncapitalize(propertyName);
- Object oldValue = PropertyUtils.getProperty(_this, propertyName);
- Object newValue = invocation.getArguments()[0];
- if (!isEquals(oldValue, newValue))
- map.put(propertyName, oldValue);
- }
- return super.invoke(invocation);
- }
- public static boolean isEquals(Object oldValue, Object newValue) {
- if (oldValue == null && newValue == null)
- return true;
- if (oldValue != null)
- return oldValue.equals(newValue);
- else
- return newValue.equals(oldValue);
- }
- }
java 代码
- import org.springframework.aop.framework.ProxyFactory;
- import org.springframework.beans.BeanUtils;
- public class Main {
- public static void main(String[] args) {
- User u1 = new User("username1", "password1");
- User u2 = new User("username2", "password2");
- ProxyFactory pc = new ProxyFactory();
- pc.setProxyTargetClass(true);
- pc.setTargetClass(u1.getClass());
- pc.addAdvice(new EditAwareMixin());
- pc.setTarget(u1);
- u1 = (User) pc.getProxy();
- BeanUtils.copyProperties(u2, u1);
- EditAware ea = (EditAware) u1;
- System.out.println(ea.isEdited("username"));
- System.out.println(ea.getOldValue("username"));
- }
- public static class User {
- private String username;
- private String password;
- public User() {
- }
- public User(String username, String password) {
- this.username = username;
- this.password = password;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
- }