Spring 4 supports Java 8 features, springjava

Source: Internet
Author: User
Tags time zones

Spring 4 supports Java 8 features, springjava

Spring framework 4 supports Java 8 and APIs. In this article, we will focus on Spring 4's support for new Java 8 features. Most importantly, Lambda expressions, method references, dates and times of the JSR-310, and repeatable comments.

Lambda expressions

The Spring code library uses a large number of functional interfaces in Java 8. Lambda expressions can be used to write cleaner and more compact code. A Lambda expression can be provided whenever an object of a function interface is expected. Let's continue to learn functional interfaces first.

Functional Interface

An interface with a single abstract method is called a functional interface. Below are some examples of functional interfaces in JDK:

Comparator is a function that only has an abstract non-object method. Although two abstract methods are declaredequalsIs a public method corresponding to the object, so it is excluded from the count. An interface with an object-class method and no non-object method is not a functional interface.

An interface is called a function interface if it has an abstract non-object class method and is extended from a non-functional interface with a unique object class method.

Example of Spring framework functional interfaces:

@FunctionalInterfaceAnnotations can be used in the top Declaration of the interface declaration, but this is not necessary. This annotation is used by the compiler to check whether this interface is a valid functional interface. If we try to define multiple single abstract methods in the interface, the compiler will throw an error.

Function Descriptor

The function descriptor of an interface is the type of an abstract method of the interface. The method type includes the parameter type, return type, and throws clause.

Example:

How to compile Lambda expressions

The syntax of Lambda expressions can be divided into three parts:

  • An arrow (->)

  • Parameter List: a Lambda expression can contain 0 or more parameter examples:() → { System.out.println(“ No arguments”); } (String arg) → { System.out.println(“ One argument : ”+arg); } (String arg1, Integer arg2) → { System.out.println(“Two arguments : ”+arg1+” and ”+arg2); }

  • Expression body: it can be a single expression or code block. A single expression is simply evaluated and returned. Example:(String arg) → { System.out.println(“ One argument : ”+arg); }If a statement block exists in the expression Body, it is determined as a method Body, and the hidden return statement after the block is executed gives control to the caller.

Now let's take a look at how to use Lambda expressions:

Example 1:

// Use a Lambda expression

Example 2:

// Use a Lambda expression

You can use the Lambda expression through the Spring callback function. For example, if you use ConnectionCallback to retrieve the list of given JDBC connections, you can write the following statement:jdbcTemplate.execute(connection -> connection.getCatalog())

Method reference

Function interfaces can also be implemented using method references to reference methods or constructors but do not call them. Method reference is similar to Lambda expressions, but method Reference refers to existing class methods. Lambda defines an anonymous method and uses it as an instance of a function interface.

A new package in Java 8 contains a function interface commonly used for Lambda expressions and method references: java. util. function.

Date Time API

The existing Date and Time classes in Java have multiple problems. One of the biggest problems with the Date and Calendar classes is that they are not thread-safe. Developers have to be especially careful about concurrency when writing date Processing code. The Date class does not support internationalization, so the time zone is not supported. Developers must write a large amount of code to support different time zones.

The Date and Time classes also show poor API design.java.util.DateThe month in the middle starts from 0, the day starts from 1, and the year starts from 1900. Consistency is missing. These other issues related to the Date and Time classes have been resolved in the new Date and Time APIs in Java 8.

Injava.timeAn important class for packaging new Date and Time APIS isLocalDate,LocalTimeAndZonedDateTime.

LocalDate and LocalTime

LocalDateIndicates that the default format for date is YYYY-MM-DD and there is no time. This is an immutable class. We can usenow()The current date obtained by the method.

NewLocalDateExample:

// Obtain the current date

You can also enter parameters for year, month, and day to create a new one.LocalDateInstance.

// April 1, 2016

LocalTimeIndicates the time without a date, which is unchanged. The default time format is hh: mm: ss. zzz.

NewLocalTimeExample:

// Obtain the current time

// 18:30:30

By default,LocalDateAndLocalTimeClass uses the system clock of the default time zone. These classes also providenew()To modify the time zone. You can passzoneidTo obtain the date in a specific time zone.

Example:

// Current local date Kolkata (India)

In addition, there is a class,LocalDateTimeThe date and time are combined. The default format is yyyy-MM-ddTHH: MM: ss. zzz ·.

// Current date and time

//

ZonedDateTime

This is an immutable class that represents the date and time that contains the time zone information. We can use an instance of this class to represent a specific event, such as a meeting in some regions of the world.

// Use the system time and default zone for the current time

// The current time uses the system clock of a specific time zone

Spring 4 provides a conversion framework that supports all classes that are part of Java 8 Date and Time APIs. Spring 4 can use a string and convert it to Java 8LocalDate. Spring 4 also supports@DateTimeFormatFormat the Java 8 Date-Time field with annotations.@DateTimeFormatDeclare a field to be formatted as date and time.

Repeated Annotation

Before Java 8, adding multiple comments of the same type to declarations or types (such as a class or method) is not allowed. As a work und, developers have to combine them into a single container annotation.

Example:

Repeated annotations allow us to rewrite the same code without explicitly using container annotations. Although the container annotation is not used here, the Java compiler is responsible for encapsulating two annotations into one container:

Example:

Define repeated annotations

Define a repeated annotation, through reusable@RepeatableAnnotation, or create an annotation with repeated annotation type series attributes.

Step 1: declare repeated annotation types:

Step 2: declare the container annotation type.

All implementations are as follows:

To obtain the annotation information at runtime@Retention(RetentionPolicy.RUNTIME)Just comment.

Search Annotation

getAnnotationsByType()OrgetDeclaredAnnotationsByType()Is a new method used to access the annotation reflection API.

Annotations can also be used through their container annotationsgetAnnotation()OrgetDeclaredAnnotation().

Conclusion

Spring 4 can also run in Java 6 and Java 7. Spring uses many functional interfaces. With Java 8 and Spring 4, you can use Lambda expressions and functional interfaces and write more clean and compact code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.