Study based on the fifth edition of Spring Actual Combat

Let’s learn Java Spring together!

Spring

introduce

At the heart of Spring is a container, often called the Spring application context, for creating and managing application components. ** These components (or beans) ** are wired together in the context of a Spring application to form a complete application.

The behavior of wiring beans together is based on a pattern called dependency injection (DI). Instead of components themselves creating and maintaining the life cycles of other beans they depend on, dependency injection applications rely on separate entities (containers) to create and maintain all components and inject those components into beans that need them. This is usually done through the constructor parameter or property accessor method.

If the Product Service relies on inventory Service (that is, an internal inventory Service is required), the framework in Spring is as follows:

The traditional way is to use XML for configuration:

<bean id="inventoryService" class="com.example.InventoryService" />
<bean id="productService" class="com.example.ProductService" >
    <constructor-arg ref="inventoryService" />
</bean>
Copy the code

But the above way is not too easy, now commonly used is the way to use Java annotations:

@Configuration: Indicates to Spring that it is a Configuration class public Class ServiceConfiguration {@bean: Public InventoryService InventoryService() {return new InventoryService(); Public ProductService ProductService() {return new ProductService(inventoryService()); }}Copy the code

The way annotations are used is based on automatic configuration and automatic scanning.

You can now use start.spring. IO/for fast spring…

For more information on Spring annotations, see Spring Annotations and Tests.

Spring MVC

Spring MVC is a Web framework that comes with Spring. At its core is the concept of a controller, which is a class that processes requests and responds with some information.

MVC is model-view-controller.

The Controller handles the corresponding network requests and designs the view (visualizing the corresponding model) using templates such as JSP or Themleaf. A model represents an object or JAVA POJO that accesses data. It can also have logic to update the controller as the data changes

How to use Spring MVC for Web application development, visible development of Web applications.

Spring and Databases

The Spring framework provides JDBC and JPA to simplify and standardize interactions with databases, greatly simplifying the time it takes to write persistence layer operations — Spring handles databases.

Spring Security

Application security has always been an important topic, and it seems to be getting more important every day. Fortunately, Spring has a robust security framework in Spring Security.

Spring Security addresses a wide range of application Security requirements, including authentication, authorization, and API Security.

Potoyang. Gitbook. IO/spring – in – a…

Spring Configuration Properties

As mentioned earlier, Spring has two configurations:

  • Bean Wiring: Declare this component as a component in Spring and how it should be injected into each other;
  • Property injection: How to set the bean in the Spring context;

It is worth mentioning that the Spring environment is a summary of all configurable properties, including:

  • JVM System Properties
  • Operating system environment variables
  • Command line arguments
  • Application properties profile

It aggregates these four properties into an environment where beans can call or inject each other.

Spring configuration properties include server, Web page, database, etc. It is recommended to query the related properties when you need to configure them, but you need to see what can be configured in advance so that you can better find them at work.

Spring integration

The Spring framework is already powerful on its own, but it can be made even stronger by integrating with other applications!

REST services

What are REST services?

REST is not a REpresentation of the word ‘REST’, but rather a shorthand for several words’ State Transfer ‘. More commonly known as: URL location of resources, using HTTP verbs (GET, POST, DELETE, PUSH, etc.) to describe operations.

What is RESTful?

Apis built based on REST are Restful.

Why Restful?

The traditional way of development is to use JSP as the presentation layer, which has a disadvantage: the need to convert the front-end static HTML pages into JSP pages, reduces the development efficiency, and let the back-end staff also need to pay attention to the front-end pages. To address this problem, front and rear end separation is used. And Restful can be unified to PC, wechat (H5), IOS or Android to provide services, the server to provide data, do not provide front-end style (front-end style is concerned by the front end!)

For details about restful operations, see restful.

For details about restful examples, see: Example.

How do I use the Rest API?

Spring applications can use REST apis in the following ways:

  • RestTemplate – A simple, synchronous REST client provided by the Spring core framework.

  • Traverson — Hyperlinks-aware synchronous REST client, provided by Spring HATEOAS, inspired by the JavaScript library of the same name.

  • WebClient – a responsive, asynchronous REST client introduced in Spring 5.

Sending asynchronous messages

Spring can use JMS to send messages, or RabbitMQ and messaging middleware such as AMQP and Kafka to send messages.

  • JMS is a Java standard that defines a common API for using message brokers.

Spring supports JMS through a template-based abstraction called JmsTemplate. Using JmsTemplate, it is easy to send messages across queues and topics from the producer side and receive them on the consumer side. Spring also supports the concept of message-driven POJOs: simple Java objects that respond asynchronously to incoming messages on queues or topics.

  • If you want to use RabbitMQ (AMQP) or Kafka messaging middleware, you need to configure it in Spring.

Integration of the Spring

With Spring configuration, you can assemble multiple components into the pipes through which data flows. In this way, messages between different components can be transmitted to each other through a transport pipe.

So how do you configure the integration flow (that is, define the data flow)?

  • Using XML, an example is as follows:
<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration" xmlns:int-file="http://www.springframework.org/schema/integration/file" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/ springintegration-file.xsd"> <int:channel id="textInChannel" /> <int:transformer id="upperCase" input-channel="textInChannel" output-channel="fileWriterChannel" expression="payload.toUpperCase()" /> <int:channel id="fileWriterChannel" /> <int-file:outbound-channel-adapter id="writer" channel="fileWriterChannel" directory="/tmp/sia5/files" mode="APPEND" append-new-line="true" /> </beans>Copy the code

The focus of the code above is on the last few lines: two channels are defined and the data transfer mode between them is set, and the last fileWriterChannel uses the int-file namespace to configure an external channel adapter to write messages to a file.

  • XML is not convenient for development and later changes in large projects. Java annotations are still better. The above XML implementation uses Java annotations in the code as follows:
@Configuration public class FileWriterIntegrationConfig { @Bean @Transformer(inputChannel="textInChannel", outputChannel="fileWriterChannel") public GenericTransformer<String, String> upperCaseTransformer() { return text -> text.toUpperCase(); } @Bean @ServiceActivator(inputChannel="fileWriterChannel") public FileWritingMessageHandler fileWriter() { FileWritingMessageHandler handler = new FileWritingMessageHandler(new File("/tmp/sia5/files")); handler.setExpectReply(false); handler.setFileExistsMode(FileExistsMode.APPEND); handler.setAppendNewLine(true); return handler; }}Copy the code
  • You can also use a DSL configuration, which instead of going through multiple beans and setting the data transfer between them, directly defines a bean to which the data flows, looking directly at the code:
@Configuration public class FileWriterIntegrationConfig { @Bean public IntegrationFlow fileWriterFlow() { return IntegrationFlows .from(MessageChannels.direct("textInChannel")) .<String, String>transform(t -> t.toUpperCase()) .handle(Files.outboundAdapter(new File("/tmp/sia5/files")) .fileExistsMode(FileExistsMode.APPEND) .appendNewLine(true)) .get(); }}Copy the code

**IntergrationFlow is an integration class in Spring.

What can be achieved using Spring Integration’s DSL?

An integration flow consists of one or more of the following components:

  • Channel: Information from one component to another;
  • Filters: Allow only some data that meets the criteria to pass through the integration stream;
  • Transformers: Perform some data processing on the message, usually converting data types;
  • Routers: Routers usually send information to one of several channels based on message headers.
  • 1. Splitters: separate messages into multiple feeds and send them to different channels;
  • Aggregators: The enemies of classifiers that aggregate messages into one.
  • Service Activators: Pass messages to Java methods and return values to output;
  • Channel Adapters: Connect channels to some external systems or transmissions.
  • Gateways: Transmits data to integration streams through corresponding interfaces.

** Spring integration is data interaction between multiple components;

The response type Spring

Reactor is a commonly used event response model.

What is a Reactor?

When we develop applications, there are two styles of code we can write — imperative and responsive:

  • Imperative (synchronous) code is a series of tasks that run one at a time, completing one task after the other. Data is processed in batches and work cannot be moved to the next task until the previous task has completed batch data processing.

  • Reactive defines a set of tasks to process data, but these tasks can be run in parallel. Each task processes a subset of these data, and as it processes another subset, passes the completed data to the next task.

A real-world analogy would be to think of imperative programming as a balloon filled with water and responsive programming as a garden hose. ** Both are ways to surprise and immerse your friends on a hot summer day. But their execution styles are different:

  • Imperative a water balloon can carry its payload at a time, soaking its intended target at the moment of impact. However, the capacity of water balloons is limited, and if you want to soak more people (or get the same person wetter), your only option is to increase the number of balloons.

  • A garden hose carries its payload as a stream of water from the faucet to the nozzle. The capacity of the garden faucet may be limited, but there is a constant supply of water during the water fight. As long as the water enters the hose from the tap, it keeps going through the hose and out of the nozzle. The same garden hose is easy to expand and you and your friends can have more fun.

Imperative programming is like a water balloon in a water fight, there’s nothing inherently wrong with it, but someone with a water hose like responsive programming has an advantage in scalability and performance.

Reactor is all about responsive programming.

Reactive flow

Reactive Stream aims to provide the standard for non-blocking asynchronous flow processing. It is summarized through four interfaces: Publisher, Subscriber, Processor, and Subscription.

  • Publisher provides data for each Subscription Subscriber, which subscribes through the Publisher interface:
public interface Publisher<T> {
    void subscribe(Subscriber<? super T> subscriber);
}
Copy the code
  • Subscriber can receive messages from Publisher once it has subscribed to subsribe.
  • Subscription is a message object that implements an interface to retrieve message data from the object.
  • The Processor connects the publisher to the subscriber, and the identity between the two changes due to the Processor (who says publishers can’t be subscribers?).

** Note: The core types of responsive programming are Mono (no more than one data item) and Flux (which can represent multiple data items).

Practical operation

See how to implement a Spring WebFlux instance.

How to implement a responsive data store example can refer to.

Spring Cloud

Micro service

Before we introduce what micro-services are, let’s take a look at how they were developed over the decades:

You create a single application of a Web service that is built into a deployable JAR or WAR file. It’s normal to develop as a monolithic application, and that’s how most applications have been built for decades. Even if you split your application into modules, you’ll still end up with a JAR or WAR file that you can push into production.

This is definitely the best way to build small, simple applications. ** But interestingly, small applications tend to grow. ** It’s easy to add more code to a project when a new feature is needed. Before you know it, your application will become a complex monolithic application.

A single application may seem simple, but it has the following problems:

  • High complexity of individual applications: The higher the complexity, the more difficult it is to understand the role of each component in the whole.
  • Testing is too difficult: the more complex the system, the more difficult integration testing is;
  • Dependencies may conflict: The dependencies of two functions may conflict with each other;
  • Not easy to scale: Even if only a small part of the functionality is changed, the whole needs to be deployed;
  • Technology selection is difficult: you are choosing a language, platform, library, etc for the overall framework;
  • Getting online is more complicated: a single function may fail and the entire system may fail.

Microservices emerged to address the shortcomings of monolithic applications: simply put, microservices architecture is a way of breaking up applications into small applications that are developed and deployed independently. These small applications (microservices) coordinate with each other to provide more complete and powerful applications.

Its advantages are the disadvantages of the above monomer application.

** Note: it doesn’t matter that we haven’t figured out microservices yet, ** because it is a concept that has not appeared for a few years, it is difficult to explain and distinguish it with previous concepts, and you will understand it slowly by looking at more information.

Eureka

As there are so many Spring Clouds, just take out Eureka of Spring Cloud Netflix to give a brief introduction.

The word Eureka expresses an exclamation of joy when one has found or discovered something. This meaning makes it the most appropriate name for a service registry. It is through Eureka that microservices discover each other.

Legend has it that Eureka was first expressed by the Greek physicist Archimedes. When he discovered buoyancy while sitting in his bathtub, he jumped out and ran home naked, Shouting “Eureka!”

** * Legend is legend after all.

Eureka acts as a central registry for all services ** in microservices applications. **Eureka itself can be thought of as a micro-service whose purpose is to help other services discover each other on a larger scale.

When a service instance is started, it registers with Eureka under its own name. If there are multiple instances of a service, they are all registered in Eureka with the same name (same name?).

When another service needs to use some service, it does not call the service by hard coding (that is, writing parameters in a function). Instead, it looks up the service by name from Eureka, and the Ribbon uses a load balancing algorithm to select a suitable service host to send to the other service.

other

For details on how Spring Cloud performs configuration management, go to Configuration Management.

For information on how Spring Cloud handles failures and delays, skip failure resolve.

Spring deployment

All of the above are Spring theories and components to consider when developing.

So how do you deploy a developed project online? Like a Web project?

The main flow is as follows:

  • Create and complete the Spring project
  • Package in JAR format (or war format if you want to deploy to a Web container)
  • Deploy and start

Please refer to the detailed operation process:

www.jianshu.com/p/3f3c0f5b1…

Thank you

Potoyang. Gitbook. IO/spring – in – a…