I answer the new features in Spring 5, the interviewer to impress me

Recently, a small partner got their satisfaction with the Offer, the process of talking to him that he's the interviewer asked him about Spring more problems, the most satisfaction is to let the interviewer to answer questions about their own knowledge Spring 5 answers good.

Spring5 in September 2017 issued a general release, it is since December 2013 the first major release of Spring. It provides some long-awaited improvements also adopted a new programming paradigm to reflect the style principles.

This version is a long time the most exciting version. Spring 5 is compatible with Java ™ 8 and JDK 9, which integrates a flow-type reaction, to provide a convenient subsequent disruptive way to achieve the endpoint, and Web application development.

Of course, this is not just reactive programming version of the theme, so many programmers still excited about the significant characteristics. It needs to be able to seamlessly extend disaster recovery and responsive service for load fluctuations is increasing, Spring 5 well positioned to meet this demand.

Here are the basic content of Java SE 8 and Java EE 7 API upgrades, new reactive programming model Spring 5, support for HTTP / 2, and Spring full support for functional programming by Kotlin. We will introduce a brief test and performance enhancements, introduced last general revision of the core and the Spring container.

Upgrade to Java SE 8 and Java EE 7

Previous Spring has been supporting some of the Java version of the abandoned, and Spring 5 from "old baggage" liberation. In order to take full advantage of Java features 8, its code base has been improved, and requires a minimum of Java 8 JDK versions.

Spring 5 is fully compatible with Java 9 based on a path (paths and modules), and it has been tested JDK 9 test suite. For Java 9 lovers, this is a good news.

At the API level, Spring 5 is compatible with Java EE 8 technology to meet the demand for Servlet 4.0, Bean Validation 2.0 and the new JSON Binding API's. Minimum requirements Java EE API for V7, this version introduces a minor version for Servlet, JPA and Bean Validation API's.

Reactive programming model

Spring 5 of the most exciting new features is its reactive programming model. Spring 5 is based on a reactive basis constructed, and is fully asynchronous and non-blocking. Only a small amount of thread, a new event loop execution model can be expanded vertically.

Spring 5 using the reaction scheme provides a mechanism to spread the flow of negative pressure in the reaction formula assembly. A negative pressure is to ensure that data from multiple producers will not make the concept of users overwhelmed.

Spring Spring WebFlux is reactive core 5, which provides two programming models for the Spring Web programming designed for developers: annotation-based model and Functional WebFramework (WebFlux.fn).

Annotation-based Spring Web MVC model is the modern alternative model based on the reaction of the foundation is built, and Functional Web Framework is based alternative @Controller annotation programming model. These models are run by the same reaction rules, which adjust to accommodate reactive nonblocking HTTP streaming API.

Use annotations to program

Web MVC programmer should be very familiar with the Spring annotation-based programming model 5, 5 adjust the Spring Web MVC's @Controller programming model, using the same notes.

In the following code BookController class provides two methods, respectively, in response to a list of books for HTTP requests and HTTP request for a given id books. Please note that the Mono and Flux and other objects. These objects are achieved in Scheme flow specification reaction formula Publisher interface type, which processes data stream responsibility. Mono object processing a stream containing only one element, and Flux represents a stream comprising N elements.

@RestController
public class BookController { //反应式控制器
@GetMapping("/book")
Flux<Book> list() {
returnthis.repository.findAll();
}
@GetMapping("/book/{id}")
Mono<Book> findById(@PathVariable String id) {
returnthis.repository.findOne(id);
}
}

These are the notes for the Spring Web programming, we use the following functional Web framework to solve the same problem.

Functional Programming

Spring functional method of the delegates the request to the processing functions which the server receives a request instance and returns a response to the type of formula. View of a piece of code, creating class BookHandler wherein listBooks () and getBook () method is equivalent to the function of the Controller.

publicclassBookHandler {
public Mono<ServerResponse> listBooks(ServerRequest request) {
return ServerResponse.ok()
.contentType(APPLICATION_JSON)
.body(repository.allPeople(), Book.class);
}
public Mono<ServerResponse> getBook(ServerRequest request) {
return repository.getBook(request.pathVariable("id"))
.then(book -> ServerResponse.ok()
.contentType(APPLICATION_JSON)
.body(fromObject(book)))
.otherwiseIfEmpty(ServerResponse.notFound().build());
}
}

By routing function to match the media parameters of the HTTP request type, client requests are routed to the handler. The following code shows the library resources endpoint URI delegates the call to the appropriate handler:

BookHandler handler = new BookHandler();
RouterFunction<ServerResponse> personRoute =
route(
GET("/books/{id}")
.and(accept(APPLICATION_JSON)), handler::getBook)
.andRoute(
GET("/books")
.and(accept(APPLICATION_JSON)), handler::listBooks);

Data stored behind these examples also supports full reactive experience which is supported by Spring Data reactive Couchbase, Reactive MongoDB and Cassandra to achieve.

The reaction using the REST endpoint performs programming

The new programming model from the traditional Spring Web MVC model, introduced some great new features.

For example, WebFlux module is provided which is completely non-blocking RestTemplate, alternative reaction scheme called WebClient. Create a WebClient below, and call books endpoint to request a given id 1234 books.

//通过WebClient调用REST端点
Mono<Book> book =WebClient.create("http://localhost:8080")
.get()
.url("/books/{id}", 1234)
.accept(APPLICATION_JSON)
.exchange(request)
.then(response -> response.bodyToMono(Book.class));

Supports HTTP / 2

HTTP / 2 improves transmission performance, reduced latency and increased throughput applications, providing a rich Web experience.

Spring 5 provide specialized HTTP / 2 feature support, also supports the people expected to occur in the JDK 9 new HTTP client. Although HTTP / 2 server push functionality has been disclosed for a long time by ServerPushFilter class Jetty Servlet engine to Spring developers, but if you find in Spring 5 out of the box provides HTTP / 2 performance enhancement, Web optimization of those who must We will be cheering for this purpose.

Spring 5.1 provides Servlet 4.0, HTTP / 2 new features will Tomcat 9.0, Jetty9.3 Undertow 1.4 and native provided.

Kotlin and Spring WebFlux

Kotlin is an object-oriented language from JetBrains support functional programming. One of its main advantages is very high and Java interoperability. Through the introduction of special support for Kotlin, Spring 5 fully absorb this advantage. Its functional programming style and Spring WebFlux module perfectly match its new routing DSL functional use of Web frameworks and clean and idiomatic code. Such can be simply expressed as endpoint routing the following code:

//Kotlin用于定义端点的路由DSL
@Bean
fun apiRouter() = router {
(accept(APPLICATION_JSON) and "/api").nest {
"/book".nest {
GET("/", bookHandler::findAll)
GET("/{id}", bookHandler::findOne)
}
"/video".nest {
GET("/", videoHandler::findAll)
GET("/{genre}", videoHandler::findByGenre)
}
}
}

When using Kotlin 1.1.4 above, it adds support (through optional parameters with default values) of Kotlin immutable classes, and API support for full support of the null.

Use Lambda Expressions Sign Bean

As an alternative to traditional XML and JavaConfig you can now use Lambda expressions registered Spring Bean, the Bean can actually registered as a provider. The following code using Lambda expressions registered a Book Bean:

GenericApplicationContext context = newGenericApplicationContext();
context.registerBean(Book.class, () ->new
Book(context.getBean(Author.class))
);

Spring Web MVC support the latest API

The new WebFlux module offers many new and exciting features, but also cater to the Spring 5 willing to continue to use Spring MVC developer needs. Spring 5 updated the "Model - View - Controller" framework is compatible with the latest version of WebFlux and Jackson 2.9 and Protobuf 3.0, and even includes support for the new Java EE 8 JSON-Binding API's.

In addition to basic server HTTP / 2 features implemented, Spring Web MVC PushBuilder Servlet 4.0 also supported by a parameter controller MVC method. Finally, Web MVC fully supports Reactor Flux objects and Mono 3.1, as well as RxJava 1.3 and RxJava 2.1, they are treated as a return value from the MVC controller method. The ultimate aim is to support the Spring Data support the new WebClient reactive and reactive repository.

Using JUnit 5 concurrent execution and test conditions

Spring 5 and 1. JUnit

Spring5 full acceptance of the functional paradigm, and support JUnit5 and its new style functional testing. Also it provides backward compatibility with JUnit 4 to ensure that does not destroy the old code.

Spring5 test suite has been enhanced in several ways, but the most obvious is its JUnit 5 support. Can now functional programming characteristic Java 8 provided in the test unit. The following code demonstrates this support:

@Test
void givenStreamOfInts_SumShouldBeMoreThanFive() {
assertTrue(Stream.of(20, 40, 50)
.stream()
.mapToInt(i -> i)
.sum() > 110, () -> "Total should be more than 100");
}

2. migrate to JUnit 5

If you JUnit 5 to upgrade to the sidelines, in-depth analysis of the two-part tutorial StevePerry will convince you to try.

Spring5 inherited the flexibility to implement multiple extensions API JUnit 5 in Spring TestContext Framework. For example, developers can use JUnit 5 test execution conditions and annotations @EnabledIf to automatically calculate a @DisabledIf SpEL (Spring Expression Language) expression, and appropriately enable or disable the test. With these annotations, Spring 5 support complex conditional test program previously difficult to achieve. SpringTextContext Framework can now concurrently execute the test.

3. Spring WebFlux perform integration testing

Spring Test now contains a WebTestClient, which supports the endpoint to perform integration testing of Spring WebFlux server. WebTestClient analog requests and responses to avoid depletion of server resources, and can bind directly to the infrastructure WebFlux server.

WebTestClient can be bound to the real server, or function or use of the controller. In the following code, WebTestClient is bound to localhost:

WebTestClient testClient = WebTestClient
.bindToServer()
.baseUrl("http://localhost:8080")
.build();

The following code will bind to WebTestClient RouterFunction:

RouterFunction bookRouter = RouterFunctions.route(
RequestPredicates.GET("/books"),
request -> ServerResponse.ok().build()
);
WebTestClient
.bindToRouterFunction(bookRouter)
.build().get().uri("/books")
.exchange()
.expectStatus().isOk()
.expectBody().isEmpty();

Pack and clean up abandoned

Spring5 terminate support for some outdated API. The same fate has Hibernate 3 and Hibernate 4, in order to support Hibernate 5, which was abandoned. In addition, Portlet, Velocity, JasperReports, XMLBeans, JDO and Guava support has also been terminated.

Clean-up work on the package level continues. Spring 5 is no longer supported beans.factory.access, jdbc.support.nativejdbc, mock.staticmock (from spring-aspects Module) or web.view.tiles2M. Tiles 3 is now the minimum requirement of Spring.

Spring core general updates and containers

Spring 5 and improved method for scanning a recognition components, the performance of large-scale projects may be raised. At present, the scanning is performed at compile time, but added the component's coordinates to the index file META-INF / spring.components file. The index is generated by a build tasks defined for the project application-specific platform.

Annotated labeled component from javax packages are added to the index, any @Index annotated with class or interface will be added to the index. Spring scanning path of a conventional type is not deleted, but is retained as a fallback option. There are many distinct performance advantages for large code base, hosting many servers Spring project will shorten the startup time.

Spring 5 also adds support for @Nullable, which optionally may be used to indicate the point of injection. Users must now be prepared to accept a null value. In addition, annotations can also be used to mark this parameter may be null, fields, and return values. @Nullable IntelliJ IDEA etc. mainly for the IDE, but can also be used and FindBugs Eclipse, so that a null value at compile-time processing becomes easier, without having to send NullPointerExceptions at runtime.

Spring Logging also improves performance, Commons Logging bridge comes out of the box. Now supported by resource abstraction defensive programming, providing isFile indicator is getFile access.

How do I see Spring 5

Spring is the most important characteristic of the new 5 reactive programming model, which stands for the extension provides seamless, responsive service based on Spring's major protection. With the adoption of Spring 5 people, the future is expected to become reactive programming language using the Java Web and enterprise application development.

Spring future will continue to reflect this commitment, because SpringSecurity, Spring Data and Spring Integration is expected to adopt reactive programming features and advantages.

In short, Spring 5 represent a shift gorgeous Spring developers greatly welcome, but also pointed out the path towards the development of other frameworks. Spring is also upgraded 5 Spring Boot, Spring Cloud provides a very rich experience, Spring is not just a framework, already it has become a programming ecology.

Guess you like

Origin www.cnblogs.com/hulianwangjiagoushi/p/11419632.html