In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What this article shares with you is about the new features of Spring 5. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Spring5 released the general version in September 2017, which is the first major Spring version since December 2013. It provides some long-awaited improvements and adopts an entirely new programming paradigm based on reactive principles.
This version is the most exciting version in a long time. Spring 5 is compatible with Java ™8 and JDK 9 and integrates reactive streams to facilitate subsequent disruptive approaches to endpoint and Web application development.
Of course, reactive programming is not only the theme of this release, but also a major feature that excites many programmers. Spring 5 satisfies the growing demand for disaster recovery and responsive services that can seamlessly scale to load fluctuations.
The following describes the basics of Java SE 8 and Java EE 7 API upgrades, Spring 5's new reactive programming model, support for HTTP/2, and Spring's full support for functional programming through Kotlin. There will also be a brief introduction to testing and performance enhancements, and finally general revisions to the Spring core and containers.
Upgrade to Java SE 8 and Java EE 7
Previous Spring has been supporting some deprecated versions of Java, while Spring 5 has been freed from the "old baggage". In order to take full advantage of the features of Java 8, its code base has been improved and requires Java 8 as the minimum JDK version.
Spring 5 is fully compatible with Java 9 on the classpath (and module path), and it has passed the JDK 9 test suite. This is good news for Java 9 enthusiasts.
At the API level, Spring 5 is compatible with Java EE 8 technology, meeting the requirements for Servlet 4.0, Bean Validation 2.0, and the new JSON Binding API. The minimum requirement for Java EE API is V7, which introduces minor versions for Servlet, JPA, and Bean Validation API.
Reactive programming model
The most exciting new feature of Spring 5 is its reactive programming model. Spring 5 is built on a reactive basis and is completely asynchronous and non-blocking. With only a small number of threads, the new event loop execution model can scale vertically.
Spring 5 uses reactive flow to provide a mechanism for propagating negative pressure in reactive components. Negative pressure is a concept that ensures that data from multiple producers do not overwhelm users.
Spring WebFlux, the reactive core of Spring 5, provides developers with two programming models designed for Spring Web programming: the annotation-based model and Functional WebFramework (WebFlux.fn).
The annotation-based model is a modern alternative to Spring Web MVC, which is built on a reactive basis, while Functional Web Framework is an alternative to the programming model based on @ Controller annotations. These models are all run by the same reactive rule, which adjusts the non-blocking HTTP to adapt to the reactive flow API.
Programming with annotations
Web MVC programmers should be familiar with the annotation-based programming model of Spring 5, which adapts Web MVC's @ Controller programming model to the same annotations.
In the following code, the BookController class provides two methods to respond to an HTTP request for a book list and an HTTP request for a book with a given id. Note objects such as Mono and Flux. These objects are reactive types that implement the Publisher interface in the reactive flow specification, and their job is to handle the data flow. The Mono object handles a stream with only 1 element, while Flux represents a stream with N elements.
@ RestControllerpublic class BookController {/ / reactive controller @ GetMapping ("/ book") Flux list () {returnthis.repository.findAll ();} @ GetMapping ("/ book/ {id}") Mono findById (@ PathVariable String id) {returnthis.repository.findOne (id);}} above are annotations for Spring Web programming. Let's use the functional Web framework to solve the same problem.
Functional programming
The functional methods of Spring 5 delegate requests to handler functions that receive an instance of a server request and return a reactive type. Take a look at a piece of code to create the BookHandler class, where the listBooks () and getBook () methods are equivalent to the functions in Controller.
PublicclassBookHandler {public Mono listBooks (ServerRequest request) {return ServerResponse.ok () .contentType (APPLICATION_JSON) .body (repository.allPeople (), Book.class);} public Mono getBook (ServerRequest request) {return repository.getBook (request.pathVariable ("id")) .then (book-> ServerResponse.ok () .contentType (APPLICATION_JSON) .body (fromObject (book) .otherwiseI fEmpty (ServerResponse.notFound (). Build ());}}
The client request is routed to the handler function by matching the HTTP request parameters with the media type through the routing function. The following code shows that the book resource endpoint URI delegates the call to the appropriate handler:
BookHandler handler = new BookHandler (); RouterFunction personRoute = route (GET ("/ books/ {id}") .and (accept (APPLICATION_JSON)), handler::getBook) .andRoute (GET ("/ books") .and (accept (APPLICATION_JSON)), handler::listBooks); the data store behind these examples also supports a complete reactive experience, which is achieved through Spring Data support for reactive Couchbase, Reactive MongoDB, and Cassandra.
Use REST endpoints to perform reactive programming
The new programming model breaks away from the traditional Spring Web MVC model and introduces some nice new features.
For example, the WebFlux module provides a completely non-blocking, reactive alternative to RestTemplate called WebClient. Let's create a WebClient and call the books endpoint to request a book with a given id of 1234.
/ / call rest endpoint Mono book = WebClient.create via WebClient ("http://localhost:8080") .get () .url (" / books/ {id} ", 1234) .accept (APPLICATION_JSON) .exchange (request) .then (response-> response.bodyToMono (Book.class)); support HTTP/2
HTTP/2 provides a rich Web experience by improving transport performance, reducing latency, and improving application throughput.
Spring 5 provides specialized HTTP/2 feature support as well as support for new HTTP clients that people expect to appear in JDK 9. Although HTTP/2 's server push functionality has been exposed to Spring developers for a long time through the ServerPushFilter class of the Jetty Servlet engine, Web optimists will cheer if they find that HTTP/2 performance enhancements are available right out of the box in Spring 5.
The new features of Spring 5.0 that provide Servlet 4.0 HTTP Charpy 2 will be provided natively by Tomcat 9.0, Jetty9.3 and Undertow 1.4.
Kotlin and Spring WebFlux
Kotlin is an object-oriented language from JetBrains that supports functional programming. One of its main advantages is its very high interoperability with Java. Spring 5 fully absorbs this advantage by introducing specialized support for Kotlin. Its functional programming style matches the Spring WebFlux module perfectly, and its new routing DSL takes advantage of the functional Web framework and clean and idiomatic code. Endpoint routing can be expressed simply as in the following code:
/ / Kotlin is used to define the route for endpoints DSL@Beanfun 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 Kotlin version 1.1.4 or above is used Support for immutable classes for Kotlin is also added (through optional parameters with default values), as well as support for API that fully supports null.
Register Bean with Lambda expressions
As an alternative to traditional XML and JavaConfig, you can now register Spring Bean with Lambda expressions so that Bean can actually register as a provider. A Book Bean is registered using the Lambda expression in the following code:
GenericApplicationContext context = newGenericApplicationContext (); context.registerBean (Book.class, ()-> new Book (context.getBean (Author.class); Spring Web MVC supports the latest API
The new WebFlux module provides many new and exciting features, but Spring 5 also caters to the needs of developers who are willing to continue to use Spring MVC. The Model-View-Controller framework has been updated in Spring 5 to be compatible with WebFlux and the latest versions of Jackson 2.9 and Protobuf 3.0, and even includes support for the new Java EE 8 JSON-Binding API.
In addition to the basic server implementation of the HTTP/2 feature, Spring Web MVC also supports PushBuilder for Servlet 4.0 through a parameter of the MVC controller method. Finally, Web MVC fully supports the Flux and Mono objects of Reactor 3.1, as well as RxJava 1.3 and RxJava 2.1, which are considered return values from MVC controller methods. The ultimate goal of this support is to support the new reactive WebClient and reactive repositories in Spring Data.
Perform conditional and concurrent tests using JUnit 5
1. JUnit and Spring 5
Spring5 fully embraces the functional paradigm and supports JUnit5 and its new functional testing style. Backward compatibility with JUnit 4 is also provided to ensure that old code is not broken.
Spring5's test suite has been enhanced in a number of ways, but the most obvious is its support for JUnit 5. You can now take advantage of the functional programming features provided in Java 8 in unit testing. The following code demonstrates this support:
@ Testvoid 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 have a wait-and-see attitude about upgrading to JUnit 5, StevePerry's two-part in-depth tutorials will persuade you to try.
Spring5 inherits the flexibility of JUnit 5 to implement multiple extended API within Spring TestContext Framework. For example, developers can use JUnit 5's conditional test execution annotations @ EnabledIf and @ DisabledIf to automatically evaluate a SpEL (Spring Expression Language) expression and enable or disable tests appropriately. With these annotations, Spring 5 supports complex conditional testing scenarios that were previously difficult to implement. SpringTextContext Framework can now execute tests concurrently.
3. Perform integration tests using Spring WebFlux
Spring Test now contains a WebTestClient that supports integration testing of Spring WebFlux server endpoints. WebTestClient uses mock requests and responses to avoid exhausting server resources and binds directly to the infrastructure of the WebFlux server.
WebTestClient can be bound to a real server or use a controller or function. In the following code, WebTestClient is bound to localhost:
WebTestClient testClient = WebTestClient .bindToServer () .baseUrl ("http://localhost:8080") .build (); the following code binds WebTestClient to RouterFunction:
RouterFunction bookRouter = RouterFunctions.route (RequestPredicates.GET ("/ books"), request-> ServerResponse.ok () .build (); WebTestClient .bindToRouterFunction (bookRouter) .build () .get () .uri ("/ books") .exchange () .uplotStatus (). IsOk () .returtBody () .isEmpty (); package cleanup and deprecation
Spring5 has terminated support for some outdated API. The doomed ones are Hibernate 3 and Hibernate 4, which were abandoned to support Hibernate 5. In addition, support for Portlet, Velocity, JasperReports, XMLBeans, JDO, and Guava has been terminated.
Cleanup continues at the package level. Spring 5 no longer supports beans.factory.access, jdbc.support.nativejdbc, mock.staticmock (from the spring-aspects module), or web.view.tiles2M. Tiles 3 is now the minimum requirement for Spring.
General updates to Spring cores and containers
Spring 5 improves the way components are scanned and identified to improve the performance of large projects. Currently, the scan is performed at compile time, and component coordinates are added to the index file in the META-INF/spring.components file. The index is generated through a platform-specific application build task defined for the project.
Components marked with annotations from the javax package are added to the index, and any classes or interfaces annotated with @ Index are added to the index. Spring's traditional classpath scanning method has not been deleted, but has been retained as a backup option. There are many obvious performance advantages for large code bases, and servers that host many Spring projects can also reduce startup time.
Spring 5 also adds support for @ Nullable, which can be used to indicate optional injection points. The consumer must now be prepared to accept null values. In addition, you can use this annotation to mark parameters, fields, and return values that can be null. @ Nullable is mainly used for IDE such as IntelliJ IDEA, but it can also be used for Eclipse and FindBugs, which makes it easier to handle null values at compile time without sending NullPointerExceptions at run time.
Spring Logging also improves performance with its own out-of-the-box Commons Logging bridge. Defensive programming is now supported through resource abstraction, providing isFile indicators for getFile access.
The primary feature of Spring 5 is the new reactive programming model, which represents a significant guarantee of providing seamless, Spring-based responsive services. With the adoption of Spring 5, reactive programming is expected to be the future of Web and enterprise application development using the Java language.
These are the new features of Spring 5. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.