当前位置:   article > 正文

切面编程+反射实现注解式开发_切面类中的invoke方法怎么写

切面类中的invoke方法怎么写

1.本文实现的是订单查询中属性字段(用户名称为空.)通过注解反射方法给customerName填充值。

  1. package com.example.hello.annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. @Target({ElementType.FIELD,ElementType.METHOD})
  7. @Retention(RetentionPolicy.RUNTIME)
  8. /**
  9. * 注解类
  10. */
  11. public @interface NeedSetValueField {
  12. Class<?> beanClass();
  13. String param();
  14. String method();
  15. String targetField();
  16. }
  1. package com.example.hello.aspect;
  2. import com.example.hello.util.BeanUtil;
  3. import org.aspectj.lang.ProceedingJoinPoint;
  4. import org.aspectj.lang.annotation.Around;
  5. import org.aspectj.lang.annotation.Aspect;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Component;
  8. import java.util.Collection;
  9. @Component
  10. @Aspect
  11. public class SetFieldValueAspect {
  12. @Autowired
  13. BeanUtil beanUtil;
  14. /**
  15. * 切面编程环绕执行
  16. * @param joinPoint
  17. * @return
  18. * @throws Throwable
  19. */
  20. @Around("@annotation(com.example.hello.annotation.NeedSetValue)")
  21. public Object doSetValue(ProceedingJoinPoint joinPoint)throws Throwable{
  22. Object result = joinPoint.proceed();
  23. // 操作结果集,得值进行设置
  24. beanUtil.setValueByCol((Collection) result);
  25. return result;
  26. }
  27. }
  1. package com.example.hello.controller;
  2. import com.example.hello.service.OrderService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class OrderController {
  8. @Autowired
  9. private OrderService orderService;
  10. /**
  11. * 分页查询order
  12. * @param customerId
  13. * @param pageNum
  14. * @param pageSize
  15. * @return
  16. * @throws Exception
  17. */
  18. @RequestMapping("query")
  19. public Object query(String customerId, int pageNum, int pageSize)throws Exception{
  20. return this.orderService.pageQuery(customerId,pageNum,pageSize);
  21. }
  22. }
  1. package com.example.hello.controller;
  2. import com.example.hello.service.OrderService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class OrderController {
  8. @Autowired
  9. private OrderService orderService;
  10. /**
  11. * 分页查询order
  12. * @param customerId
  13. * @param pageNum
  14. * @param pageSize
  15. * @return
  16. * @throws Exception
  17. */
  18. @RequestMapping("query")
  19. public Object query(String customerId, int pageNum, int pageSize)throws Exception{
  20. return this.orderService.pageQuery(customerId,pageNum,pageSize);
  21. }
  22. }
  1. package com.example.hello.dao;
  2. import com.example.hello.model.User;
  3. import com.sun.org.glassfish.gmbal.ParameterNames;
  4. import org.springframework.cache.annotation.Cacheable;
  5. import java.util.List;
  6. @Cacheable
  7. public class UserDao {
  8. void insert(User u) {
  9. }
  10. void update(User u){}
  11. /**
  12. * 查询用户列表
  13. * @param username
  14. * @return
  15. */
  16. List<User> query( String username){
  17. return null;
  18. }
  19. /**
  20. * 根据id查询用户
  21. * @param id
  22. * @return
  23. */
  24. User find(String id){
  25. User user = new User("1","1");
  26. return user ;
  27. }
  28. }
  1. package com.example.hello.model;
  2. import com.example.hello.annotation.NeedSetValueField;
  3. import com.example.hello.dao.UserDao;
  4. import java.io.Serializable;
  5. public class Order implements Serializable {
  6. /**
  7. * list={id:1,cid:1,cname:null}
  8. */
  9. private static final long serialVersion = 100000000L;
  10. private String id;
  11. private String customerId;
  12. /**
  13. * 通过注解实现给customerName赋值
  14. */
  15. @NeedSetValueField(beanClass = UserDao.class,param = "customerId",method = "find",targetField = "name")
  16. private String customerName; //set值 后置方法---反射 user--find-->method.invoke()--->name---获取到具体值
  17. // --->set
  18. public String getId() {
  19. return id;
  20. }
  21. public void setId(String id) {
  22. this.id = id;
  23. }
  24. public String getCustomerId() {
  25. return customerId;
  26. }
  27. public void setCustomerId(String customerId) {
  28. this.customerId = customerId;
  29. }
  30. public String getCustomerName() {
  31. return customerName;
  32. }
  33. public void setCustomerName(String customerName) {
  34. this.customerName = customerName;
  35. }
  36. }
  1. package com.example.hello.model;
  2. public class User {
  3. private static final long serialVersion = 100000001L;
  4. public String getId() {
  5. return id;
  6. }
  7. public void setId(String id) {
  8. this.id = id;
  9. }
  10. private String id;
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. private String name;
  18. public User(String id,String name){
  19. this.id = id;
  20. this.name = name;
  21. }
  22. }
  1. package com.example.hello.service;
  2. import com.example.hello.annotation.NeedSetValue;
  3. import com.example.hello.dao.OrderDao;
  4. import com.example.hello.model.Order;
  5. import com.github.pagehelper.Page;
  6. import com.github.pagehelper.PageHelper;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Service;
  9. @Service
  10. public class OrderService {
  11. /**
  12. * 1.获取和设置组件
  13. * 2.首先,当调用组件时,我怎么知道设置哪些属性值
  14. * 3,这个要告诉我
  15. * 4.我怎么知道哪个bean的哪个方法,以及要传入的值
  16. * 5.这个要告诉我
  17. */
  18. @Autowired
  19. private OrderDao orderDao;
  20. // 执行本方法进行切面
  21. // 自定义注解切面
  22. @NeedSetValue
  23. public Page<Order> pageQuery(String customerId, int pageNum, int pageSize)throws Exception{
  24. Page<Order> page = PageHelper.startPage(pageNum,pageSize);
  25. this.orderDao.query(customerId);
  26. // 批量查询10
  27. // util --- setField(class bean,params,setField) ---可以解决问题
  28. // 更加优雅的方法,不用改动原有的代码
  29. // 使用AOP进行增强处理,对结果进行设置,再返回
  30. // annotion 注解,能让类附上说明信息到运行期
  31. return page;
  32. }
  33. }
  1. package com.example.hello.util;
  2. import com.example.hello.annotation.NeedSetValueField;
  3. import org.apache.commons.lang.StringUtils;
  4. import org.springframework.beans.BeansException;
  5. import org.springframework.context.ApplicationContext;
  6. import org.springframework.context.ApplicationContextAware;
  7. import org.springframework.stereotype.Component;
  8. import java.lang.reflect.Field;
  9. import java.lang.reflect.Method;
  10. import java.util.Collection;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. @Component
  14. public class BeanUtil implements ApplicationContextAware {
  15. private ApplicationContext applicationContext;
  16. @Override
  17. public void setApplicationContext(ApplicationContext var1) throws BeansException{
  18. this.applicationContext = applicationContext;
  19. }
  20. public void setValueByCol(Collection col)throws Exception{
  21. Class<?> clazz = col.iterator().next().getClass();
  22. Field[] fields = clazz.getDeclaredFields();
  23. Map<String,Object> cache = new HashMap<>();
  24. for (Field field: fields) {
  25. NeedSetValueField sv = field.getAnnotation(NeedSetValueField.class); //拿到定义在属性上的注解
  26. if (sv == null)continue;
  27. field.setAccessible(true);
  28. Object bean = this.applicationContext.getBean(sv.beanClass()); // 得到bean(UserDao)
  29. // bean中找到方法 ---find方法
  30. Method method = sv.beanClass().getMethod(sv.method(),clazz.getDeclaredField(sv.param()).getType());
  31. // customerId
  32. Field paramField = clazz.getDeclaredField(sv.param());
  33. paramField.setAccessible(true);
  34. Field targetField = null;
  35. Boolean needInnerField = StringUtils.isNotEmpty(sv.targetField());
  36. String keyPrefix = sv.beanClass()+"-"+sv.method()+"-"+sv.targetField()+"-";
  37. for (Object obj:col) {
  38. Object paramValue = paramField.get(obj); // 3
  39. if (paramValue == null) continue;
  40. Object value = null;
  41. String key = keyPrefix;
  42. if (cache.containsKey(key)){
  43. value = cache.get(key);
  44. }else {
  45. value = method.invoke(bean,paramValue); // User == value
  46. if (value != null){
  47. if (needInnerField){
  48. if (targetField == null){
  49. targetField = value.getClass().getDeclaredField(sv.targetField());
  50. }
  51. value = targetField.get(value); // user中的名字tony
  52. }
  53. }
  54. cache.put(key,value);
  55. }
  56. field.set(obj,value); //field ---customerName
  57. }
  58. // 参数具体的值
  59. // method.invoke();
  60. }
  61. }
  62. }
  1. package com.example.hello;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestParam;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @SpringBootApplication
  10. @EnableEurekaClient
  11. @RestController
  12. public class ServiceHelloApplication {
  13. public static void main(String[] args) {
  14. SpringApplication.run(ServiceHelloApplication.class, args);
  15. }
  16. @Value("${server.port}")
  17. String port;
  18. @RequestMapping("/hello")
  19. public String home(@RequestParam(value = "name", defaultValue = "toher") String name) {
  20. return "hi " + name + " ,this is Feign Project , i am from port:" + port;
  21. }
  22. }

项目结构:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/225440
推荐阅读
相关标签
  

闽ICP备14008679号