Home Java javaTutorial Detailed introduction to the Java8 features supported by Spring 4 (picture)

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Mar 21, 2017 am 10:48 AM
java8

Spring Framework 4 supports Java 8 language and API features. In this article, we focus on Spring 4’s support for the new Java 8 features. The most important ones are Lambda expression, method reference, JSR-310 date and time, and repeatable annotations. Let’s take a look with the editor below

Spring Framework 4 supports Java 8 language and API functions. In this article, we focus on Spring 4’s support for the new Java 8 features. The most important ones are lambda expressions, method references, JSR-310 date and time, and repeatable annotations.

Lambda expressions

Spring's code base uses a large number of functional interfaces in Java 8, and Lambda expressions can be used to write cleaner and more compact code. We can provide a Lambda expression whenever an object of a functional interface is expected. Let us first learn about functional interfaces before proceeding further.

Functional interface

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

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Comparator is only one abstraction Functions of non-object methods. Although two abstract methods are declared, equals is excluded from the count because it is a public method corresponding to the object. An interface that has one object class method and no non-object methods is not a functional interface.

Detailed introduction to the Java8 features supported by Spring 4 (picture)

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

Detailed introduction to the Java8 features supported by Spring 4 (picture)

#Example of functional interface of Spring framework:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Detailed introduction to the Java8 features supported by Spring 4 (picture)

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

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Function descriptor

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

Example:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

How to write Lambda expression

The syntax of Lambda expression can be split into three Part:

  • An arrow (–>)

  • Parameter list: A Lambda expression can contain 0 or more parameters. Example:

  • () → { 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); }
    Copy after login
  • Expression body: It can be a single expression or a code block. A single expression will simply be evaluated and returned. Example: (String arg) → { System.out.println(“ One argument : ”+arg); } If there is a statement block in the expression body (Body), then it will be determined as a method body, and after the block is executed A hidden return statement gives control to the caller.

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

Example 1:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

// Using Lambda Expression

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Example 2:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

//Using Lambda expression

Detailed introduction to the Java8 features supported by Spring 4 (picture)

You can use Lambda expressions through Spring's callback functions. For example, using a ConnectionCallback to retrieve the list of given JDBC connections can be written as the following statement: jdbcTemplate.execute(connection -> connection.getCatalog())

Method Reference

Functional interfaces can also be implemented using method references, which reference methods or constructors but do not call them. Method references and Lambda expressions are similar, but a method reference refers to a method of an existing class, whereas a Lambda defines an anonymous method as an instance of a functional interface.

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

Date Time API

There are multiple issues with the existing Date and Time classes in Java. 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 issues when writing date-handling code. The Date class also does not support internationalization and therefore does not support time zones. Developers have to write a lot of code to support different time zones.

The Date and Time classes also exhibit poor API design. The month in java.util.Date starts from 0, the day starts from 1, and the year starts from 1900. Consistency is lacking. These and several other issues with the Date and Time classes are now resolved in the new Date and Time APIs in Java 8.

The important classes of the new Date and Time API under the java.time package are LocalDate, LocalTime and ZonedDateTime.

LocalDate and LocalTime

LocalDate's default format for representing dates is YYYY-MM-DD, without time. This is an immutable class. We can get the current date using now() method.

Example of creating a new LocalDate instance:

//Get the current date

Detailed introduction to the Java8 features supported by Spring 4 (picture)

We can also enter the year, month, and day Parameters to create a new LocalDate instance.

// April 1, 2016

Detailed introduction to the Java8 features supported by Spring 4 (picture)

LocalTime represents a dateless time and is unchanged. The default format for time is hh:mm:ss.zzz.

Example of creating a new LocalTime instance:

//Get the current time

Detailed introduction to the Java8 features supported by Spring 4 (picture)

// 18:30:30

Detailed introduction to the Java8 features supported by Spring 4 (picture)

By default, the LocalDate and LocalTime classes use the system clock in the default time zone. These classes also provide support for modifying the time zone through the overloaded new() method. You can get a date in a specific time zone by passing zoneid.

Example:

//Current local date Kolkata (India)

Detailed introduction to the Java8 features supported by Spring 4 (picture)

In addition, there is a class, LocalDateTime that combines date and Time, the default format is yyyy-MM-ddTHH:MM:ss.zzz·.

//Current date and time

Detailed introduction to the Java8 features supported by Spring 4 (picture)

// 2016-04-01 13:30

Detailed introduction to the Java8 features supported by Spring 4 (picture)

ZonedDateTime

This is an immutable class used to represent a date and time including time zone information. We can use an instance of this class to represent a specific event, such as a conference in some part of the world. //The current time uses the system time and default zone

Detailed introduction to the Java8 features supported by Spring 4 (picture)//The current time uses the system clock of a specific time zone

Detailed introduction to the Java8 features supported by Spring 4 (picture)Spring 4 provides a transformation framework that supports all classes that are part of the Java 8 date and time API. Spring 4 can take a

string

of 2016-9-10 and convert it into an instance of Java 8 LocalDate. Spring 4 also supports formatting Java 8 Date-Time fields via the @DateTimeFormat annotation. @DateTimeFormat declares that a field should be formatted as a date time.

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Duplicate annotations

Before Java 8, adding multiple annotations of the same type to a declaration or type (such as a class or method) is not allowed. As a workaround, developers had to combine them into a single container annotation.

example:

Duplicate 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 the two annotations into a container:

Example:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Define repeating annotations

Define a repeating annotation, annotate it through the reusable @Repeatable annotation, or create an annotation with a repeating annotation type series attribute .

Step 1: Declare the repeating annotation type:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

Step 2 Step: Declare the container annotation type.

Detailed introduction to the Java8 features supported by Spring 4 (picture)

The entire implementation is as follows:

Detailed introduction to the Java8 features supported by Spring 4 (picture)

In order to obtain annotations at runtime For information, just annotate it with @Retention(RetentionPolicy.RUNTIME).

Retrieve annotations

getAnnotationsByType() or getDeclaredAnnotationsByType() are new methods in the Reflection API for accessing annotations.

Annotations can also be accessed through their container annotations using getAnnotation() or getDeclaredAnnotation().

Conclusion

Spring 4 also runs on Java 6 and Java 7. Since Spring uses a lot of functional interfaces, with Java 8 and Spring 4, you will be able to use Lambda expressions and functional interfaces and write cleaner, more compact code.

The above is the detailed content of Detailed introduction to the Java8 features supported by Spring 4 (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to calculate date one year ago or one year later in Java 8? How to calculate date one year ago or one year later in Java 8? Apr 26, 2023 am 09:22 AM

Java8 calculates the date one year ago or one year later using the minus() method to calculate the date one year ago packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo09{publicstaticvoidmain(String[]args ){LocalDatetoday=LocalDate.now();LocalDatepreviousYear=today.minus(1,ChronoUni

How to calculate date one week later using Java 8? How to calculate date one week later using Java 8? Apr 21, 2023 pm 11:01 PM

How to calculate the date one week later in Java8 This example will calculate the date one week later. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks, and months. The ChronoUnit class declares these time units. Since LocalDate is also an immutable type, you must use variables to assign values ​​after returning. packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassDemo08{publicstaticvoidmain(String[

How to use the Clock class in Java8 How to use the Clock class in Java8 Apr 25, 2023 pm 03:37 PM

Java8's Clock class Java8 adds a Clock class for obtaining the current timestamp, or date and time information in the current time zone. Where System.currentTimeInMillis() and TimeZone.getDefault() were used before, they can be replaced by Clock. packagecom.shxt.demo02;importjava.time.Clock;publicclassDemo10{publicstaticvoidmain(String[]args){//Returnsthecurrenttimebase

How to deal with time zones in Java8 How to deal with time zones in Java8 Apr 27, 2023 pm 09:22 PM

Handling time zones in Java 8 Java 8 not only separates date and time, but also separates time zones. There are now a series of separate classes such as ZoneId to handle specific time zones and ZoneDateTime to represent time in a certain time zone. This was done by the GregorianCalendar class before Java8. The following example shows how to convert the time in this time zone to the time in another time zone. packagecom.shxt.demo02;importjava.time.LocalDateTime;importjava.time.ZoneId;importjava.time.ZonedDateT

How to get the current timestamp in Java8 How to get the current timestamp in Java8 May 01, 2023 am 11:46 AM

Get the current timestamp in Java8. The Instant class has a static factory method now() that returns the current timestamp, as shown below: packagecom.shxt.demo02;importjava.time.Instant;publicclassDemo16{publicstaticvoidmain(String[]args) {Instanttimestamp=Instant.now();System.out.println("Whatisvalueofthisinstant"+timestamp.t

How to use predefined formatting tools to parse or format dates in Java8 How to use predefined formatting tools to parse or format dates in Java8 Apr 28, 2023 pm 07:40 PM

How to use predefined formatting tools to parse or format dates in Java8 packagecom.shxt.demo02;importjava.time.LocalDate;importjava.time.format.DateTimeFormatter;publicclassDemo17{publicstaticvoidmain(String[]args){StringdayAfterTommorrow="20180205 ";LocalDateformatted=LocalDate.parse

How to get today's date in Java8 How to get today's date in Java8 May 01, 2023 pm 06:49 PM

Get today's date in Java8 LocalDate in Java8 is used to represent today's date. Unlike java.util.Date, it only has dates and does not include time. Use this class when you only need to represent dates. packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo01{publicstaticvoidmain(String[]args){LocalDatetoday=LocalDate.now();System.out.println("Today’s date:&q

How to determine whether two dates are equal in Java8 How to determine whether two dates are equal in Java8 May 02, 2023 am 08:46 AM

Determine whether two dates are equal in Java8 packagecom.shxt.demo02;importjava.time.LocalDate;publicclassDemo04{publicstaticvoidmain(String[]args){LocalDatedate1=LocalDate.now();LocalDatedate2=LocalDate.of(2018,2,5) ;if(date1.equals(date2)){System.out.println("Times are equal");}e

See all articles