Giter VIP home page Giter VIP logo

spring-study's Introduction

spring-study

java spring and spring-boot study

spring-study's People

Contributors

zjblog avatar

Watchers

 avatar  avatar

spring-study's Issues

工厂模式

工厂模式包括:

  1. 简单工厂模式(并不是一个设计模式,由于经常使用,所以归为了工厂模式中)
    uml图如下
    default

  2. 工厂方法模式
    uml如下
    default

  3. 抽象工厂模式
    uml图如下
    default

在此项目的patterm包下有以上模式的例子,有更详细的介绍.
ps:画UML使用的工具是在线的,非常好用,试试看

Java Integer的缓存

Integer a = 11;
Integer b = 11;
Integer c = 300;
Integer d = 300;
System.out.println(a == b);
System.out.println(c == d);

两次打印是否都是true或false呢?

你一定会想在Java 中,== 比较的是对象引用,而 equals 比较的是值.不同的对象有不同的引用,所以在进行比较的时候都应该返回 false.但奇怪的是,第一个是true第二个是false.原因应该出在包装类上,查看了下源码顺便重新认识下包装类.
Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing)这相当于调用 valueOf() 方法.查看valueOf()方法

 /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

在创建新的 Integer 对象之前会先在 IntegerCache.cache 中查找,IntegerCache类来负责 Integer 的缓存.IntegerCache 是 Integer 类中一个私有的静态类,Javadoc说明这个类是用来实现缓存,并支持 -128 到 127 之间的自动装箱过程.最大值127 可以通过 JVM的启动参数 -XX:AutoBoxCacheMax=size 修改. 缓存通过一个 for 循环实现,从小到大的创建整数并存储在一个名为 cache 的整数数组中,这个缓存会在 Integer 类第一次被使用的时候被初始化出来,在自动装箱的时候就可以使用缓存中包含的实例对象,而不是创建一个新的实例.这种Integer 缓存策略仅在自动装箱的时候有用,使用构造器创建的Integer 对象不能被缓存.

Integer f = 10; // autoboxing
Integer g = new Integer("10");// Constructs

变量f可是使用缓存g是构造不能使用缓存,所以f==g 是false.
这种缓存行为不仅适用于Integer对象一下包装类也有缓存

  • ByteCache 用于缓存 Byte 对象
  • ShortCache 用于缓存 Short 对象
  • LongCache 用于缓存 Long 对象
  • CharacterCache 用于缓存 Character 对象
    Byte、Short、Long 有固定范围: -128 到 127.对于Character范围是0 到127.除了Integer 可以通过参数改变范围外,其它的都不行.
    ps:像Double Float这种浮点数是没有缓存的,没办法缓存.其它的类型-128-127最多就是255个对象,并且使用的比较多.缓存初始化时也需要耗费一定时间.

单例模式

5

java中实现单例的几种方式,写了几种常用的.具体的代码查看singleton包下的代码(推荐使用枚举创建单例)

Spring Aop 中使用表达式定义切点

_通过execution函数定义切点表达式(定义切点的方法切入)
execution(<访问修饰符> <返回类型><方法名>(<参数>)<异常>)
_

eg:

  1. execution(public * _(..)) # 匹配所有public方法.
  2. execution(_ com.fq.dao._(..)) # 匹配指定包下所有类方法(不包含子包)
  3. execution(_ com.fq.dao.._(..)) # 匹配指定包下所有类方法(包含子包)
  4. execution(_ com.fq.service.impl.OrderServiceImple._(..)) # 匹配指定类所有方法
  5. execution(_ com.fq.service.OrderService+._(..)) # 匹配实现特定接口所有类方法
  6. execution(_ save*(..)) # 匹配所有save开头的方法

Comparable and Comparator

Comparable And Comparator对比

Comparable

Comparable可排序的 若一个类实现了该接口意味着该类支持排序.如果有一个实现Comparable接口的类的对象的List或数组,则该List 或数组可以通过 Collections.sort或Arrays.sort进行排序.如Intege的集合(Integer String已经默认实现了Comparable接口)用于一个对象的不同实例去比较.Comparable接口只有一个方法 public int compareTo(T o);返回值<0 =0 >0

Comparator

是比较器接口.如果要控制某个类的次序而此类本身不支持排序(即没有实现Comparable接口),我们可以建立一个“该类的比较器”来进行排序.这个“比较器”只需要实现Comparator接口即可.jdk8之后Comparator变成了函数式接口,书写起来更方便.

 List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 20; i++) {
            list.add(i + new Random().nextInt(20));
        }
        System.out.println(list);
        // 不需要提供额外比较器 因为Integer默认已经实现了Comparable接口
        Collections.sort(list);
        System.out.println(list);
 List<Person> list1 = new ArrayList<>();
        Person person = null;
        for (int i = 0; i < 5; i++) {
            person = new Person();
            person.setName("" + i);
            person.setAge(i + new Random().nextInt(20));
            list.add(person);
        }

        System.out.println(list.toString());
        // 因为person并没有实现Comparable接口 所以我们要定义一个比较器 jdk8中lambda的写法
        Collections.sort(list1, (a, b) -> a.getAge() - b.getAge());
        System.out.println(list.toString());

SpringMVC @RequestMapping的使用

@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上.用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径.相信大家都有一定的了解.

  • value:请求的实际地址,指定的地址可以是URI Template 模式,可以是一个字符串也可是是个字符串数组,数组代表多个请求映射到同一个方法.value={"/test","/test1"}.String[] value() default {};
  • path:作用和value一样String[] path() default {};
  • method: 指定请求的method类型,GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS等.可以指定多个请求方式method={RequestMethod.POST,RequestMethod.GET}.RequestMethod[]
  • params:请求中必须包含某些参数值才能访问方法.
    @RequestMapping(path = "/login", params={"ok="false"}) 这个方法只处理login上有ok参数值为false的请求.
  • headers:请求头信息,通过设置头信息限制客户端的请求.String[] headers()
    @RequestMapping(path = "/login", headers="Host=localhost")只接收本机发来的请求
  • consumes:处理指定提交内容类型的请求.同一个路径对应不同MediaType可以处理不同的请求
    MediaType.MULTIPART_FORM_DATA_VALUE 处理文档上传类型的请String[] consumes() 求,MediaType.APPLICATION_JSON_VALUE处理Content-Type 是json类型的请求.
  • produces:请求返回的类型.MediaType.APPLICATION_JSON_UTF8_VALUE返回json数据.String[] produces()
  • name:Assign a name to this mapping.String

只有name返回String其它都是String[]

使用元注解自定义注解

  1. @target
    Target说明了Annotation所修饰的对象范围,ElementType中包含(TYPE--用于描述类、接口(包括注解类型) 或enum声明FIELD--属性描述包括enum常量METHOD--方法描述PARAMETER--参数描述CONSTRUCTOR--构造描述LOCAL_VARIABLE--局部变量描述ANNOTATION_TYPE--注解描述PACKAGE--包描述TYPE_PARAMETER--该注解能写在类型变量的声明语句中TYPE_USE--该注解能写在使用类型的任何语句中) 更详细的内容请看此文章
  2. @retention
    Retention表示注解的生命周期。RetentionPolicy中包含(SOURCE--在源文件中有效CLASS--在class文件中有效RUNTIME--运行时有效)
  3. @documented
    Documented是一个标记注解,可以被javadoc此类的工具文档化
  4. @inherited
     Inherited是一个标记注解,Inherited阐述了某个被标注的类型是被继承的

自定义注解

  格式:public @interface 注解名 {定义体}

Annotation类型里面的参数设定

  • 只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型
  • 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和 String,Enum,Class,annotations数据类型以及这一些类型的数组.例如,String value();这里的参数成员就为String  
  • 如果只有一个参数成员,最好把参数名称设为"value",后加小括号
  • 简单的demo请看此项目中的Annotation包中的demo

Spring 多线程定时执行任务

  • @EnableScheduling 使用在类上,表示该类可以被Spring调度.详细的请参考javadoc
  • @scheduled 我经常使用fixedRate和cron的方式进行定时任务的执行

    如果不进行额外的配置,以上的任务是单线程执行,下面介绍多线程执行任务的配置.

    Spring-boot项目都会有一个被@configuration注解的类,让此类实现SchedulingConfigurer接口,实现configureTasks方法.如下
 @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }
    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(50);
    } ```
使用的@Bean(destroyMethod="shutdown")是为了确保当Spring应用上下文关闭的时候任务执行者也被正确地关闭.
具体可参考本项目

BlockingQueue核心方法及常用的实现类

BlockingQueue

  • 堵塞队列.在新增的Concurrent包中,BlockingQueue很好的解决了多线程中线程安全的问题,通过这些线程安全的队列类,我们可以更方便的写出线程安全的程序.
  • BlockingQueue的实现类有很多,其中ArrayBlockingQueue LinkedBlockingDeque比较常用.其中LinkedBlockingDeque放入和取出数据的时候用的不是同一把锁,比ArrayBlockingQueue 根高效一点.
  • poll()取出一个元素,没有返回null,不会堵塞队列.
  • take()取出一个元素,如果没有会堵塞队列,直到有元素.
  • add(o)放入元素,如果满了会抛出异常IllegalStateException
  • offer(o)放入元素,放入成功返回true
  • put(o)放入元素,会堵塞队列,直到放入成功
  • 其它方法请参考javadoc
  • 此项目BlockingQueueTest下有BlockingQueue的Demo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.