- quaff
- 等级:
- 性别:
- 文章: 380
- 积分: 336
- 来自: 天朝
|
先定义一个需要被introduce的interface
java 代码
- public interface EditAware {
-
- public Object getOldValue(String propertyName);
-
- public boolean isEdited(String propertyName);
-
- }
再写这个interface的mixin
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);
- }
- }
最后是怎么使用这个mixin
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;
- }
-
- }
- }
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|