利用注解和AOP实现属性赋值

文章目录


问题:查询订单方法需要获取用户姓名。现有用户表和订单表,订单表里存储了客户id。
分析:不能关联查用户的姓名,但用户的姓名又需要,总是需要获取用户的。
一般做法:查询订单信息,循环拿出客户id,查用户表,取出用户姓名,在赋值给订单类中的客户姓名。
以上做法存在哪些问题呢?
单一原则,查询订单信息 需要在去查用户信息。
开放 关闭原则,开扩展开放,对修改关闭。假如别的地方也需要用到查询订单信息,那么这个类里面冗余了其他业务代码。整个方法无法使用。

如果只是对方法进行动态扩展。有的时候需要增强方法,有的时候用原来方法就能解决问题。可以采用注解加aop方式解决
先来自定义两个注解
1.作用于哪个类和哪个方法

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NeedSetValue {
    Class<?> beanClass();
    String param();
    String method();
    String targetFiled();
}

2.需要对哪个属性赋值

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface NeedSetValueFeild {
}

3.定义aop切面

@Component
@Aspect
public class SetFeildValueAspect {
    @Autowired
    BeansUtil beansUtil;
    @Around("@annotation(com.st.user.annotation.NeedSetValueFeild)")
    public Object dosetFeildValue(ProceedingJoinPoint pjp)throws Throwable{
          Object ret=pjp.proceed();
          //操作结果集
        //获取到注解 然后通过反射执行 方法
        beansUtil.setFeildValueForCol((Collection) ret);
        return ret;
    }
}

4.bean的工具类

public class BeansUtil implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void setFeildValueForCol(Collection col) throws Exception {
        Class<?> clazz = col.iterator().next().getClass();
        Field[] fields = clazz.getDeclaredFields();
        HashMap<String, Object> cache = new HashMap<>();
        for (Field needField : fields) {
            NeedSetValue sv = needField.getAnnotation(NeedSetValue.class);
            if (sv == null)
                continue;
            needField.setAccessible(true);
            Object bean = this.applicationContext.getBean(sv.beanClass());
            Method method = sv.beanClass().getMethod(sv.method(), clazz.getDeclaredField(sv.param()).getType());
            Field paramFiled = clazz.getDeclaredField(sv.param());
            paramFiled.setAccessible(true);
            Field targetFiled = null;
            Boolean needInnerFile = !StringUtil.isEmpty(sv.targetFiled());
            String keyPrefix = sv.beanClass() + "-" + sv.method() + "-" + sv.targetFiled() + "-";
            for (Object obj : col) {
                Object paramValue = paramFiled.get(obj);
                if (paramValue == null)
                    continue;
                Object value = null;
                String key = keyPrefix + paramValue;
                if (cache.containsKey(key)) {
                    value = cache.get(key);
                } else {
                    value = method.invoke(bean, paramValue);
                    if (needInnerFile) {
                        if (value != null) {
                            if (targetFiled == null) {
                                targetFiled = value.getClass().getDeclaredField(sv.targetFiled());
                                targetFiled.setAccessible(true);
                            }
                            value = targetFiled.get(value);
                        }
                    }
                    cache.put(key, value);
                }
                needField.set(obj, value);
            }

        }
    }
}

5.来看以下如何设置调用:

   @NeedSetValueFeild
    public Page<Order> pageQuery(String customerId, int pageNum, int pageSize){
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        this.orderDao.query(customerId);
        return page;
    }

6.在哪里需要赋值就在那个属性上添加,这里我们在Order类上使用注解

    @NeedSetValue(beanClass = UserDao.class,param = "customerId",method = "find",targetFiled = "name")
    private String customerName;
    //UserDao中的find方法: select * from user where id="xxx" 返回user对象
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP是Spring框架中的一个重要模块,它提供了面向切面编程(AOP)的支持。AOP是一种编程思想,它可以在不改变原有代码的情况下,通过在程序运行时动态地将代码“织入”到现有代码中,从而实现对原有代码的增强。 Spring AOP提供了基于注解AOP实现,使得开发者可以通过注解的方式来定义切面、切点和通知等相关内容,从而简化了AOP的使用。 下面是一个基于注解AOP实现的例子: 1. 定义切面类 ```java @Aspect @Component public class LogAspect { @Pointcut("@annotation(Log)") public void logPointcut() {} @Before("logPointcut()") public void beforeLog(JoinPoint joinPoint) { // 前置通知 System.out.println("执行方法:" + joinPoint.getSignature().getName()); } @AfterReturning("logPointcut()") public void afterLog(JoinPoint joinPoint) { // 后置通知 System.out.println("方法执行完成:" + joinPoint.getSignature().getName()); } @AfterThrowing(pointcut = "logPointcut()", throwing = "ex") public void afterThrowingLog(JoinPoint joinPoint, Exception ex) { // 异常通知 System.out.println("方法执行异常:" + joinPoint.getSignature().getName() + ",异常信息:" + ex.getMessage()); } } ``` 2. 定义业务逻辑类 ```java @Service public class UserService { @Log public void addUser(User user) { // 添加用户 System.out.println("添加用户:" + user.getName()); } @Log public void deleteUser(String userId) { // 删除用户 System.out.println("删除用户:" + userId); throw new RuntimeException("删除用户异常"); } } ``` 3. 在配置文件中开启AOP ```xml <aop:aspectj-autoproxy/> <context:component-scan base-package="com.example"/> ``` 在这个例子中,我们定义了一个切面类LogAspect,其中通过@Aspect注解定义了一个切面,通过@Pointcut注解定义了一个切点,通过@Before、@AfterReturning和@AfterThrowing注解分别定义了前置通知、后置通知和异常通知。 在业务逻辑类中,我们通过@Log注解标注了需要增强的方法。 最后,在配置文件中,我们通过<aop:aspectj-autoproxy/>开启了AOP功能,并通过<context:component-scan>扫描了指定包下的所有组件。 这样,当我们调用UserService中的方法时,就会触发LogAspect中定义的通知,从而实现对原有代码的增强。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值