Spring提供的各种工具

Spring提供的各种工具

github地址
https://github.com/xc-lin/springboot-utils.git
希望大家可以多多关注

  1. copyProperties(Object source, Object target) 通过这个方法可以快速的将source对象中的属性复制到target中,前提是两个对象中有相同的属性名以及对应的属性方法。
    示例:

     Source source = new Source("111", "222");
     Target target = new Target();
     BeanUtils.copyProperties(source,target);
     System.out.println(target);
     // Target{id=null, address='222'}
    
  2. 排序器

    1. 实现方式:实现Ordered接口
    @Data
    public class Bean1 extends AbstractBean implements Ordered {
       private String name = "Bean1";
    
       @Override
       public int getOrder() {
           return 1;
       }
    }
    

    并使用OrderComparator()排序器

     List<AbstractBean> beans = Arrays.asList(new Bean3(), new Bean2(), new Bean1());
     System.out.println("排序前:"+beans);
     beans.sort(new OrderComparator());
     System.out.println("排序后:"+beans);
    
    1. 实现方式:使用@Order(1)注解
    @Data
    @Order(1)
    public class AnnotationBean1 extends AbstractBean {
       private String name = "Bean1";
    }
    

    并使用AnnotationAwareOrderComparator()排序器

    List<AbstractBean> beans = Arrays.asList(new AnnotationBean3(), new AnnotationBean2(), new AnnotationBean1());
       System.out.println("排序前:"+beans);
       beans.sort(new AnnotationAwareOrderComparator());
       System.out.println("排序后:"+beans);
    
  3. 资源工具类

    @SpringBootApplication
    public class ResourceUtilsApplication {
        public static void main(String[] args) {
            ApplicationContext applicationContext = SpringApplication.run(ResourceUtilsApplication.class, args);
            Resource resource = applicationContext.getResource("classpath:banner.txt");
            System.out.println(resource.getFilename());
        }
    }
    
  4. 类的元数据读取器,是通过直接读取.class来获得的

    public static void main(String[] args) throws IOException {
        SimpleMetadataReaderFactory simpleMetadataReaderFactory = new SimpleMetadataReaderFactory();
        MetadataReader metadataReader = simpleMetadataReaderFactory.getMetadataReader("com.lxc.metainfoutils.bean.AnnotationBean");
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        System.out.println(classMetadata.getClassName());
    
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        for (String annotationType : annotationMetadata.getAnnotationTypes()) {
            System.out.println(annotationType);
        }
    }
    

动态代理工具类

  1. 动态代理工具类:ProxyFactory()
    此工具类可以自动判断使用jdk动态代理还是cglib动态代理,其中会判断被代理类是否实现了接口

    public static void proxyFactoryTest(){
        UserService userService = new UserService();
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.setTarget(userService);
        proxyFactory.addAdvice((MethodInterceptor) invocation -> {
            Object proceed =null;
            try {
                System.out.println("before......");
                proceed = invocation.proceed();
                System.out.println("afterReturning......");
            }catch (Exception e){
                System.out.println("afterThrowing.......");
            }finally {
                System.out.println("after....");
            }
            return proceed;
        });
        UserService proxy = (UserService) proxyFactory.getProxy();
        proxy.test(1);
    
    }
    
  2. 动态代理工具类:`返回一个factoryBean可以放入ioc容器中

    public static void main(String[] args) {
    
        // proxyFactoryTest();
        ConfigurableApplicationContext applicationContext = SpringApplication.run(ProxyUtilsApplication.class, args);
        UserService bean = applicationContext.getBean(UserService.class);
        bean.test(1);
    }
     /**
     * 返回一个factoryBean可以放入ioc容器中
     * @return
     */
    @Bean
    public ProxyFactoryBean proxyFactoryBean(){
        UserService userService = new UserService();
    
        ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
        proxyFactoryBean.setTarget(userService);
        proxyFactoryBean.addAdvice((MethodInterceptor) invocation -> {
            Object proceed =null;
            try {
                System.out.println("before......");
                proceed = invocation.proceed();
                System.out.println("afterReturning......");
            }catch (Exception e){
                System.out.println("afterThrowing.......");
            }finally {
                System.out.println("after....");
            }
            return proceed;
        });
        return proxyFactoryBean;
    
    }
    
  3. 动态代理工具类:直接代理ioc容器中的bean

    		@Configuration
    public class BeanNameAutoProxyCreatorTest {
        @Bean
        public MethodInterceptor methodInterceptor(){
            return invocation -> {
                Object proceed =null;
                try {
                    System.out.println("before...beanNameAutoProxyCreator...");
                    proceed = invocation.proceed();
                    System.out.println("afterReturning...beanNameAutoProxyCreator...");
                }catch (Exception e){
                    System.out.println("afterThrowing...beanNameAutoProxyCreator....");
                }finally {
                    System.out.println("after..beanNameAutoProxyCreator..");
                }
                return proceed;
            };
        }
        @Bean
        public BeanNameAutoProxyCreator beanNameAutoProxyCreator(){
            BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
            // 代理名为userSer开头的所有bean
            beanNameAutoProxyCreator.setBeanNames("userSer*");
            beanNameAutoProxyCreator.setInterceptorNames("methodInterceptor");
            return beanNameAutoProxyCreator;
    
        }
    }
    
    
  4. 动态代理工具类:使用反射更加灵活的代理各种类

    @Configuration
    @Import(DefaultAdvisorAutoProxyCreator.class)
    public class DefaultPointCutAdvisorTest {
        @Bean
        DefaultPointcutAdvisor defaultPointcutAdvisor(){
            DefaultPointcutAdvisor defaultPointcutAdvisor = new DefaultPointcutAdvisor();
            defaultPointcutAdvisor.setPointcut(new Pointcut() {
                @Override
                public ClassFilter getClassFilter() {
                    return clazz -> {
                        if (clazz== UserService.class){
                            return true;
                        }
                        return false;
                    };
                }
    
                @Override
                public MethodMatcher getMethodMatcher() {
                    return new MethodMatcher() {
                        @Override
                        public boolean matches(Method method, Class<?> targetClass) {
                            if ("test".equals(method.getName())){
                                return true;
                            }
                            return false;
                        }
    
                        @Override
                        public boolean isRuntime() {
                            return false;
                        }
    
                        @Override
                        public boolean matches(Method method, Class<?> targetClass, Object... args) {
                            throw new UnsupportedOperationException("Illegal MethodMatcher usage");
                        }
                    };
                }
            });
            defaultPointcutAdvisor.setAdvice((MethodInterceptor) invocation -> {
                Object proceed =null;
                try {
                    System.out.println("before...DefaultAdvisorAutoProxyCreator...");
                    proceed = invocation.proceed();
                    System.out.println("afterReturning...DefaultAdvisorAutoProxyCreator...");
                }catch (Exception e){
                    System.out.println("afterThrowing...DefaultAdvisorAutoProxyCreator....");
                }finally {
                    System.out.println("after..DefaultAdvisorAutoProxyCreator..");
                }
                return proceed;
            });
            return defaultPointcutAdvisor;
    
        }
    }
    

类型转换工具类

  1. 使用jdk自带的类型转换器,并将其设置进spring中
    @Component
    public class StringToOrderServicePropertyEditor extends PropertyEditorSupport {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            OrderService orderService = new OrderService();
            orderService.setOrderName(text);
            this.setValue(orderService);
        }
    }
    
    @Configuration
    public class EditorConfig {
        @Bean
        public CustomEditorConfigurer customEditorConfigurer(){
            CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
            Map<Class<?>, Class<? extends PropertyEditor>> customEditors  = new HashMap<>();
            customEditors.put(OrderService.class,StringToOrderServicePropertyEditor.class);
            customEditorConfigurer.setCustomEditors(customEditors);
            return customEditorConfigurer;
        }
    }
    
    @Service
    @Data
    public class UserService {
        @Value("123")
        private OrderService orderService;
    }
    
  2. 使用TypeConverter自动选择
    DefaultConversionService defaultConversionService = new DefaultConversionService();
    defaultConversionService.addConverter(new StringToOrderServiceConverter());
    SimpleTypeConverter simpleTypeConverter = new SimpleTypeConverter();
    simpleTypeConverter.registerCustomEditor(OrderService.class,new StringToOrderServicePropertyEditor());
    simpleTypeConverter.setConversionService(defaultConversionService);
    OrderService orderService = simpleTypeConverter.convertIfNecessary("1111", OrderService.class);
    System.out.println(orderService);
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值