About the book
This book
IO on the SpringFramework module documentation of the core, but this book is not just a simple translation, I will give some code according to the corresponding module operation practice and give the corresponding source analysis, The SpringFramework documentation is one of the best written of all open source frameworks in my opinion, But it can be difficult for beginners or those with less practical experience. Here is not only the document is in English form, but also according to the overview of the document is more difficult to understand and apply to the practice of project development, here requires developers to accumulate the corresponding project practice experience. So in the process of translating SpringFramework, I will continue to write corresponding sample codes, combine documents and source code analysis to achieve a better understanding. In later books, I will probably translate the popular microservices framework SpringBoot, SpringCloud and other Spring modules such as SpringData, SpringSession, SpringSecurity, etc. SpringFramework plays a cornerstone role in the whole Spring system, SpringBoot based on the Corresponding expansion of SpringFramework includes: Automatic configuration, external configuration, componentization (Start mode), etc., and SpringCloud based on SpringBoot for the whole micro-service system of service governance, service registration discovery, unified configuration center to do the relevant integration and unified related abstraction such as: SpringCloud Commons. The corresponding SpringFramework is mainly divided into the following modules for parsing: Spring core, testing, data storage, Web Servlet, Web Reactive, and integration.
version
The currently selected Version, Version 5.2.7.RELEASE, is analyzed.
The constraint
- Use bold font to mark key keywords
- Use a gray wireframe to identify technical terms
- This article describes the document structure using different levels
- The first and second level classification of the article should be preserved in English as far as possible without translation (it can help readers to locate the original text quickly).
- Example code address: gitee.com/newitman/Sp…
- This book began to write time 2020-05-05
The author
Personally engaged in the financial industry, I have worked in chongqing’s first-class technical team of Yiji Pay, Sijian Technology and an online car hailing platform, and now I am working in a bank responsible for the construction of unified payment system. I have a strong interest in the financial industry. It also practices big data, data storage, automated integration and deployment, distributed microservices, responsive programming, and artificial intelligence. At the same time, he is also keen on technology sharing, creating public accounts and blog sites to share knowledge system.
Blog: Youngitman.tech
CSDN:blog.csdn.net/liyong10288…
Wechat Official Account:
An overview of the
Spring makes it easier for developers to create enterprise-level applications. It offers just about any technology architecture in the enterprise Java ecosystem, Groovy and Kotlin support for JVMS, and the flexibility to create multiple architectures based on your application’s needs. Spring requires JDK1.8+ as of Spring Framework 5.1, and also provides out-of-the-box support for JDK 11 LTS. Java SE 8 Update 60 is recommended as the lowest Java 8 patch release, but the most recent patch release is generally recommended.
Spring supports a wide range of application scenarios. In large enterprises, applications can exist for a long time and need to run on JDk, while the application’s upgrade maintenance life cycle is out of the developer’s control. Others may run as separate JARS or embedded, or they may run in the cloud. It could also be a standalone application that does not require a server (for example, batch processing, integration load).
Groovy and Kotlin, like Java, can be compiled into JVM supported bytecode formats and run in the JVM.
Spring is an open source framework. Spring has a very strong and active community that provides constant feedback on a wide range of real-world application cases. This has contributed to Spring’s long-term success.
What We Mean by “Spring”
Spring terms mean different things in different contexts. In this context, Spring refers to the SrpingFramework project itself. Over time, however, other Spring projects have been built on top of the SrpingFramework. For the most part, what we mean by Spring is the entire project architecture. This document focuses on the Spring Framework Framework itself.
The SpringFramework is divided into modules. The application selects the appropriate module as needed. Core container module is the core including: configuration model, dependency injection mechanism. In addition, SpringFramework provides some basic support for different application architectures, messaging, transactional data and persistence, and the web. It also includes a Servlet-based SpringMVC Web framework and a Web framework that supports the Reactive programming model of WebFlux.
One thing to note about modules: Spring’s framework JARS allow deployment to JDK9’s module path. For use in jigsaw-enabled applications, the Spring Framework 5 JAR comes with automatic module name list entries that define stable language-level module names independent of the JAR (spring.core, Spring.context, etc.) names (these jars follow the same naming pattern, using – instead of., for example, spring-core and spring-context). Of course, Spring’s framework JARS work on JDK 8 and 9 classpath.
History of Spring and the Spring Framework
Spring was born in 2003 because of the complexity of the earlier J2EE specification, and although some people think That Java EE competes with Spring, Spring is actually a complement to Java EE. The Spring programming model does not include the Java EE platform specification. Instead, it carefully selected specifications for integration
- Servlet API (JSR 340)
- WebSocket API (JSR 356)
- Concurrency Utilities (JSR 236)
- JSON Binding API (JSR 367)
- Bean Validation (JSR 303)
- JPA (JSR 338)
- JMS (JSR 914)
- JTA/JCA(Distributed Transaction)
The SpringFramework also supports dependency injection (JSR 330) and the Common annotation specification (JSR 250), which application developers can choose to use in place of the Spring-specific mechanisms provided by the Spring framework.
Java EE 7(Servlet 3.1+, JPA 2.1+) also provides out-of-the-box integration with Java EE 8’s latest API (JSON Binding API), This makes Spring more compatible with service containers such as Tomcat 8, Tomcat 9, WebSphere 9, JBoss EAP 7.
Over time, the role of J2EE in application development has changed. In the early days of J2EE and Spring, applications needed to be deployed on application servers. Now, with the help of SpringBoot, these applications can be created in devOps and friendly fashion, with Servlet container embedding and some minor changes. Starting with SpringFramework5.0, WebFlux applications do not even require direct use of the Servlet API and can run directly on non-servlet container servers.
Spring continues to innovate and evolve. In addition to Spring Framework, there are other projects, such as Spring Boot, Spring Security, Spring Data, Spring Cloud, Spring Batch, etc. Keep in mind that each project has its own source code repository, issue tracker, and release rhythm. Check out spring. IO/Projects for a complete list of Spring projects.
Design Philosophy
When you’re learning a framework, it’s important to know not only what it does, but what principles it follows. The following are the guiding principles of the Spring framework.
- Spring provides choice at all levels. Let developers postpone design decisions as long as possible. For example, you can use the configuration to switch data persistence schemes without changing the code. The same can be said for many other infrastructure issues and integration with third-party apis.
- Be open to different viewpoints.
Spring
Support flexibility and have no opinion on how things should be done. It supports a wide range of application requirements with different perspectivesSpring
The design is quite flexible, how to accomplish logic processingSpring
Will not interfere) - Spring preserves strong backward compatibility. Spring’s evolution is carefully managed to ensure that changes between releases are kept to a minimum. Spring chooses JDK and third-party library versions carefully to facilitate the maintenance of spring-dependent applications and libraries.
- Spring’s API is well designed. Spring has spent a lot of time and effort designing apis that will be available in many versions and over many years.
- High code quality requirements. The Spring framework places great emphasis on being meaningful, current, and accurate
javadoc
. It is one of the few projects where the code structure is clean and there are no cyclic dependencies between packages.
Spring core
The IoC Container
1.1 Spring IoC containers and beans
This section mainly covers the principle of inversion of control for IoC containers by the SpringFramework. IoC is also known as dependency injection (DI). This is the process by which an object defines its dependencies (that is, other objects it works with) only through constructor parameters, factory method parameters, or properties set on the object instance when the object instance is constructed or returned from the factory method. This process is essentially a reverse process (hence Control Inversion) of a bean that controls the instantiation or location of its dependencies using a direct construction of the class or a mechanism such as a service locator pattern. (Note: The literal meaning is to inject a dependent instance into an instance object, including constructor injection, object property injection, setXXX method injection, etc.)
Org. Springframework. Beans and org. Springframework. Context package is the foundation of springframework container. The BeanFactory interface provides an advanced configuration mechanism capability to manage any type of object. ApplicationContext is a subinterface of the BeanFactory. Added the following capabilities:
- Easier integration
Spring
theAOP
features - Message resource processing (internationalization)
- Event publisher
- Application-specific context, for example, corresponding to the Web application context
WebApplicationContext
In short, BeanFactory provides the configuration framework and basic functionality, while ApplicationContext provides more enterprise-level functionality. ApplicationContext is a complete BeanFactory super, described in this section only as a Spring container. See The BeanFactory for more ApplicationContext replacement uses.
In Spring, the objects that make up the skeleton of your application and are managed by the container are called beans. Beans are objects that are instantiated, wrapped, and managed by the Spring container. Beans are also one of many objects in our application. Beans and their dependencies are reflected through the container’s configuration metadata.
Refer to the sample code: com. Liyong. Ioccontainer. Ioccontainer
1.2 Overview of the Spring IoC container
Org. Springframework. Context. ApplicationContext interface on behalf of the Spring IoC container, at the same time have a responsibility to instantiate, configure, and assemble of these beans. The container obtains configuration metadata to know which objects need to be instantiated, configured, and assembled. This configuration metadata comes in XML, Java annotations, or Java Config. It allows you to express the objects that make up your application and the rich interdependencies between those objects.
Some implementations of ApplicationContext are provided in Spring. In a separate application, usually by ClassPathXmlApplicationContext or FileSystemXmlApplicationContext instance to create a container. XML is the traditional way to define configuration metadata, and you can instruct the container to use Java annotations or Java Config as metadata formats, enabling these additional metadata configuration formats by providing a small amount of XML configuration declarations.
In most application scenarios, the instantiation of one or more instances of the Spring IoC container shown is not necessary. For example, in A Web application scenario, a simple XML configuration description in an application web.xml file is usually sufficient. Using the Spring Tools for Eclipse tool, we can easily create boilerplate configurations.
The following illustration shows how Spring works. Our application classes (business classes) are combined with configuration metadata. After the ApplicationContext is created and instantiated, we have a complete configuration and executable application system.
1.2.1 Configuring Metadata
As shown in the figure above, the Spring container retrieves configuration metadata. How is this metadata represented or configured? As a developer, tell the Spring container in your application how to instantiate, configure, and assemble these objects.
The XML format is a traditional way of configuring metadata, and much of this chapter uses these key concepts and features.
Xml-based configuration metadata is not the only configuration method allowed. The Spring container itself is decoupled from this configuration metadata. Today, most developers use Java Base Configuration as the way to configure Spring applications.
More metadata configurations for Spring containers are listed below:
- Annotation-based configuration: Support for annotation metadata configuration has been introduced since Spring 2.5
- Based on theJava-base configurationMethod: fromSpring 3.0To start,
Spring
theJavaConfigProject to becomeSpringFramework
A number of features are provided at the core of the. Therefore, we can useJava ConfigIs defined externallybeanRather thanXMLFile. We can use these new feature annotations for example:@Configuration
,@Bean
,@Import
和@DependsOn
.
Spring configuration definitions that comprise at least one bean, usually more than one bean, are container-managed. Xml-based configuration metadata configates these beans as elements within top-level elements. Java Config usually uses @Bean annotations to annotate methods while the class is annotated by @Configuration.
These bean definitions correspond to real bean object instances from which our application is built. For example, we define the Service layer, the data storage layer (DAO), the display layer (Queues), the Struts Action instance, the Hibernate SessionFactories instance, the JMS Queues, etc. Typically, there is no need to configure fine-grained domain objects in the container, because daOs and business logic are typically responsible for creating and loading domain objects. However, you can use Spring’s integration with AspectJ to configure objects created outside the control of the IoC container.
The following uses metadata based on XML configuration
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<! -- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<! -- collaborators and configuration for this bean go here -->
</bean>
</beans>
Copy the code
Refer to the sample code: com. Liyong. Ioccontainer. XmlIocContainer
- The ID attribute represents the unique ID of a bean
- The class attribute represents the full path type name of the bean. For example:
com.liyong.ioccontainer.ConfigruationService
1.2.2 Container Instantiation
The ApplicationContext constructor provides one or more string path parameters for the container to load configuration metadata for external resources, such as the local file system or Java classpath.
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml"."daos.xml");// Load services. XML and daos.xml configuration metadata
Copy the code
After we learn about the Spring IoC container, we may want to know more about the abstraction of Resource, which provides a convenient mechanism to read an input stream from a location defined by URI syntax. In particular, Resource is used to build the context of the application. Application context and Resource path.
The following shows the metadata configuration for the services.xml service layer
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<! -- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<! -- additional collaborators and configuration for this bean go here -->
</bean>
<! -- more bean definitions for services go here -->
</beans>
Copy the code
The data capture layer dao.xml configuration file is shown below
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<! -- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
<! -- additional collaborators and configuration for this bean go here -->
</bean>
<! -- more bean definitions for data access objects go here -->
</beans>
Copy the code
In the previous example, the service layer consists of the PetStoreServiceImpl class and the Data store layer JpaAccountDao and JpaItemDao objects (based on JPA’s object-relational mapping). The attribute name element refers to the attribute name of the JavaBean, and the ref element refers to the name of the other bean definition. The association between ID and REF expresses the dependencies of the collaborating object. For more information about configuring object Dependencies, see Dependencies.
-
Compose XML-based configuration metadata
Configuration metadata can span multiple XML configuration files. Typically, each independent XML configuration file represents a logical layer or module within the project schema.
You can use the ApplicationContext constructor to load the bean definition from these configured XML fragments. This constructor can use multiple resources to locate a Resource, as you can see in the example above. Alternatively, use one or more tag elements to load the bean definition from other XML configuration files. The following example shows importing multiple resource files.
<beans> <import resource="services.xml"/> <import resource="resources/messageSource.xml"/> <import resource="/resources/themeSource.xml"/> <bean id="bean1" class="..."/> <bean id="bean2" class="..."/> Copy the code
In the above example, the beans loaded externally are loaded from three files: services.xml, messageSource. XML, and themeSource. The paths of all imported files are corresponding to the locations of imported files. XML must be in the same directory or classpath as the import file, and messageSource. XML and themeSource. XML must be in the Resources path of the import file. As you can see/ignored. However, since these paths are relative, it is best not to use slashes.
One possible use of using.. / to reference the parent directory file, but not recommended. Doing so will result in the dependency of the current application on external files. In particular, this referencing method is not recommended when using classpath: and URL combinations (e.g. Classpath :.. /services.xml), where the runtime parsing process selects the nearest classpath root and then looks at its parent directory. Changes to the classpath configuration can cause other wrong directories to be selected.
We should always use a fully qualified resource path to replace relative path: for example, file: C: / config/services. The XML or classpath: / config/services. The XML. Note, however, that you are coupling the configuration of your application to a specific absolute location. It is usually best to reserve indirect use of such absolute locations, such as through ${… } placeholder.
The namespace itself provides the import directive feature. In addition to normal bean definitions, other configuration capabilities are provided in the XML namespace selection provided by Spring – for example, the context and util namespaces
-
Groovy’s bean definition
As a further example of external configuration metadata, the bean definition can be expressed using Spring’s Groovy language definition (which you can learn from the Grails framework). Typically, this configuration is named.groovy. Here’s an example:
beans { dataSource(BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" settings = [mynew:"setting"] } sessionFactory(SessionFactory) { dataSource = dataSource } myService(MyService) { nestedBean = { AnotherBean bean -> dataSource = dataSource } }Copy the code
}
The configuration format above corresponds to the 'bean' definition of XML and supports the **XML** namespace configuration of Spring. This approach allows us to import the 'bean' definition of **XML** via the 'importBeans' directive. > < span style = "max-width: 100%; clear: both; min-height: 1em; ` com. Liyong. Ioccontainer. ImportXmlIocContainer ` # # # # # # 1.2.3 containers use ` ApplicationContext ` is able to maintain different beans and their dependencies of senior registry interface of the factory. We can retrieve our bean instance object by using the 'T getBean(String Name, Class<T> requiredType)' method. 'ApplicationContext' allows us to read the bean definition and get the bean instance object, for example: ` ` ` Java / / create the container and load the bean definition ApplicationContext context = new ClassPathXmlApplicationContext (" services. XML ", "daos. XML"); PetStoreService service = Context.getBean ("petStore", petstoreService.class); // use configured instance List<String> userList = service.getUsernameList();Copy the code
With the Groovy configuration, the boot is very similar. But it’s an implementation of a different Context. For example:
ApplicationContext context = new GenericGroovyApplicationContext("services.groovy"."daos.groovy");
Copy the code
The most flexible variants are GenericApplicationContext combines the proxy of reader – for example: through XmlBeanDefinitionReader reads the XML file configuration information. For example:
GenericApplicationContext context = new GenericApplicationContext();
// Load configuration metadata in XML
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml"."daos.xml");
context.refresh();
Copy the code
We can also use GroovyBeanDefinitionReader load Groovy configuration file. For example:
GenericApplicationContext context = new GenericApplicationContext();
// Load groovy configuration metadata
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy"."daos.groovy");
context.refresh();
Copy the code
We can also mix or match a reader agent within the same ApplicationContext to read bean definition configuration information from different configuration sources.
We can also use the getBean() method to get our bean instance object. The ApplicationContext interface also provides several other methods to get bean instances, but ideally our code does not use them directly. Indeed, our application code should not call the getBean() method directly, so as not to couple Spring’s API (Note: In my opinion, Spring is currently a container-managed specification and standard, and using apis to couple applications is fine, unless you want to replace the underlying container. Such as: The Spring-integrated Web framework (generally referred to as SpringMVC) provides variants of the Dependency injection Controllers (Controllers) and JSF-managed bean objects for Web framework components, It also allows us to declare a dependency on a given bean through metadata (e.g., annotation injection: @autoWired, @Resource).
Technical Exchange Group: