Spring is an open source framework at the design level, which solves the problem of loose coupling between the business logic layer and other layers. Therefore, it puts the thought of interface oriented programming throughout the whole system application.

This course will explain the core technologies of Spring IoC and AOP in a simple way, and analyze the source code of the framework. Let everyone quickly grasp the principle and application of the framework.

What is the Spring framework?

Spring is a lightweight Java development framework created in 2003 to address the complexities of enterprise application development. At the heart of Spring are inversion of Control (IoC) and section-oriented programming (AOP). Spring is a lightweight open source framework that can be used in Java SE/EE.

Spring’s main role is to “decouple” code, reducing the coupling between codes. The idea is to let the relationships between objects (modules and modules) be specified not using code associations, but through configuration. That is, the relationship of objects (modules) is explained in Spring.

Spring uses Ioc to decouple business objects based on the functional characteristics of the code. IoC removes the need for the main business to maintain its own relationship in the process of calling each other, that is, to create objects to use. Instead, it is managed by the Spring container and automatically “inject,” which means assign. AOP maximizes the reuse of system-level services, which are no longer manually “mixed” into the main business logic by programmers, but “woven” into it by the Spring container.

Liverpoolfc.tv: spring. IO /

The advantages of Spring?

Spring is a framework, a half-finished piece of software. It consists of 20 modules. It’s a container-managed object, containers are things, Spring containers don’t hold text, numbers. It’s an object. Spring is a container for storing objects.

(1) Light weight

The Jars used by the Spring framework are small, typically under 1M or a few hundred KILobytes. The total number of jars required for Spring core functionality is around 3M.

The Spring framework consumes fewer resources and runs efficiently. Do not rely on other jars

(2) For interface programming, decoupling

Spring provides Ioc inversion of control, container-managed objects, and object dependencies. The way objects were created in program code is now done by containers. Dependency decoupling between objects.

(3) AOP programming support

Through the AOP function provided by Spring, it is convenient to carry out section-oriented programming. Many functions that are not easy to use in traditional OOP implementation can be easily handled by AOP. In Spring, developers can be freed from the complicated transaction management code and flexibly manage transactions through declarative way. Improve development efficiency and quality.

(4) Convenient integration of various excellent frameworks

Spring does not exclude a variety of good open source frameworks. Instead, Spring makes them easier to use. Spring provides direct support for a variety of good frameworks such as Struts,Hibernate, MyBatis, etc. Simplify the use of frameworks.

Spring is like a plug board, and other frameworks are plugs that can be easily put together. Whichever frame you want to use, put this plug in the plugboard. It doesn’t need to be easily removed.

Spring Architecture

Spring consists of more than 20 modules, They can be divided into Data Access/Integration, Web, aspect oriented programming (AOP, Aspects, Instrumentation, Messaging, Core Containers, and Tests.

IoC inversion of control

An IoC is an Inversion of Control. It refers to transferring the right to call objects, which are traditionally controlled directly by program code, to the container, through which objects are assembled and managed. Inversion of control is a transfer of control over an object from the program code itself to an external container. Through the container to achieve object creation, attribute assignment, dependency management.

IoC is a concept, an idea, and it can be implemented in a variety of ways. Dependency injection is the most popular implementation. Widely used.

Dependency: The classA class contains instances of classB and calls methods of classB in classA to complete functions. That is, classA has dependencies on classB.

Implementation of Ioc:

Dependency Injection: DI(Dependency Injection), the program code does not do location query, these work is done by the container itself.

DI means that when a program is running and needs to call another object for assistance, it does not need to create the called in the code. Instead, it relies on the external container, which creates the called object and passes it to the program. Spring’s dependency injection has few requirements on callers and callees and fully supports the management of dependencies between objects.

The Spring framework implements IoC using dependency injection (DI).

The Spring container is a mega-factory that creates and manages all the Java objects, called beans. The Spring container manages the dependencies between beans in the container, and Spring uses dependency injection to manage the dependencies between beans. Use IoC to achieve decoupling and between objects.

Preparing development tools

Development tools: IDEa2017 above dependency management: Maven3 above JDK :1.8 above

Need to set up maven native repository:

Spring’s first program

Example: 01 – primay

Creating a Maven project

Introducing maven dependency pom.xml

Define interfaces and entity classes

Create the Spring configuration file

Create an XML file in the SRC /main/resources/ directory. The file name is optional, but Spring suggests applicationContext.xml.

Spring configuration requires a constraint file, which is the XSD extension, to work properly.

  • : Used to define an instance object. One instance corresponds to one bean element.
  • Id: This attribute is the unique identity of the Bean instance. The application accesses the Bean through the ID attribute, and the dependencies between beans are also related through the ID attribute.
  • Class: Specifies the class to which the Bean belongs. Note that this is only a class, not an interface.

Defining test classes

Use Spring to create non-custom class objects

Spring configuration file adds java.util.Date definition:

MyTest test class:

Calls to the getBean (” myDate “); Gets the date class object.

Container interfaces and implementation classes

ApplicationContext Interface (container)

ApplicationContext loads Spring configuration files and acts as a “container” in your program. There are two implementation classes.

A. The configuration file is in the classpath

If the Spring configuration file stored in the project classpath, use the ClassPathXmlApplicationContext implementation class is loaded.

B. Assembly timing of objects in ApplicationContext

The ApplicationContext container assemps all the objects in the container at once when the container object is initialized. To use these objects in future code, you just need to fetch them directly from memory. High execution efficiency. But it takes up memory.

C. Java objects created using the Spring container

Xml-based DI

Example: project DI-XML

Injection of classification

After the bean instance calls the no-argument constructor to create the object, it initializes the properties of the bean object. Initialization is done automatically by the container and is called injection.

According to the different injection methods, there are two commonly used types: set injection and construct injection.

(1) Set injection (master)

Set injection, also called set value injection, is passing in the instance of the caller through setter methods. This method of injection is simple and intuitive, so it is used extensively in Spring’s dependency injection.

A. Simple type

Create java.util.Date and set the initial Date and time:

Spring configuration file:

Test method:

B. Reference type

When you specify that an attribute value of a bean is an instance of another bean, the reference relationship between them is specified by ref. The value of ref must be the ID value of a bean.

For references to other Bean objects, use the ref attribute of the label

Test method:

(2) Structural injection (understanding)

Construction injection means that the instantiation of the called is completed at the same time that the caller instance is constructed. That is, use a constructor to set up dependencies.

Example 1:

The attributes in the tag used to specify parameters are:

Name: Specifies the parameter name.

Index: indicates the number of arguments corresponding to the constructor, starting at 0. However, this property does not work, but note that if the parameters are of the same type or contain each other, you need to ensure that the assignment order is the same as the order of the parameters in the constructor.

Example 2:

Create a system class File object using construct injection

The test class:

Automatic injection of reference type properties

Injections that reference type attributes are also not shown in the configuration file. You can implicitly auto-inject reference type attributes by setting the autowire attribute value for the tag (default is not auto-inject reference type attributes). According to the different judgment criteria of automatic injection, it can be divided into two types:

  • ByName: automatic injection byName
  • ByType: automatic injection byType

(1) byName automatic injection

When the id value of the called bean in the configuration file is the same as the attribute name of the calling bean class in the code, the byName method can be used to have the container automatically inject the called bean into the caller bean. The container implements automatic injection by comparing the attribute name of the caller’s bean class with the id of the called bean in the configuration file.

For example:

(2) byType automatic injection

ByType automatic injection requires that the class specified by the class attribute of the called bean in the configuration file be of the same type as a reference type attribute of the caller bean class in the code. That is, they are either identical or have an IS-A relationship (subclass, or implementation class). But there can only be one such homologous called bean. More than one, and the container doesn’t know which one to match.

For example:

Specify multiple Spring configuration files for your application

In practical applications, with the increase of application scale, the number of beans in the system also increases greatly, resulting in huge and bloated configuration files. To avoid this situation and improve the readability and maintainability of the configuration file, you can split the Spring configuration file into multiple configuration files.

Configuration files containing relationships:

There is a master file in a configuration file, and the master file imports other subfiles. In Java code, you only need to initialize the container using the total configuration file.

For example:

Code:

Spring configuration file:

Wildcard * may also be used. However, the parent configuration file name is required to be in a format that * can match, otherwise circular recursive inclusion will occur. In this case, the parent configuration file does not match the format of Spring -*.xml, that is, cannot be named spring-total.xml.

Annotation-based DI

Example: di-Annotation project

Using annotations for DI eliminates the need to declare bean instances in the Spring configuration file. Using annotations in Spring requires some changes to the existing Spring runtime environment.

A component scanner needs to be configured in the Spring configuration file to scan for annotations in the specified base package.

There are three ways to specify multiple packages:

  1. Use multiple context:component-scan to specify different package paths

  1. Specify a delimiter for the value of the base-package

You can use commas (,) and semicolons (;) for separators. You can also use Spaces, which are not recommended.

Comma separated:

Semicolon separation:

  1. Base-package is specified to the parent package name

The value table of the base-package is the base package, and the container starts to scan the annotations in the package and its children, as well as the children below the children. So base-package can specify a parent package.

Or the top-level parent package

However, you are not advised to use the top-level parent package because there are too many paths to scan, which slows down the container startup time. Specify to target package and appropriate. That is, the package path of the annotation. The annotated classes, for example, are in the com.bjPowerNode. beans package

Define the Bean annotation @Component(Master)

You need to use the @Component annotation on the class whose value property specifies the ID value of the bean.

Example: di01

In addition, Spring provides three annotations to create objects:

  • @Repository is used to annotate DAO implementation classes
  • @service is used to annotate the Service implementation class
  • @Controller is used to annotate the Controller implementation class

The @Service annotation creates business layer objects that can be added to transaction functions, and the @Controller annotation creates objects that can be used as handlers to receive user requests.

@repository, @service, and @Controller are refinements of the @Component annotations that annotate objects at different layers. That is, persistence layer objects, business layer objects, and control layer objects.

@Component does not specify a value property, and the bean ID is the first letter of the class name.

Simple type attribute injection @Value(Master)

You need to use the annotation @Value on the attribute, whose Value attribute specifies the Value to be injected.

When property injection is done using this annotation, there is no need for setters in the class. Of course, if the property has a setter, you can add it to the setter as well.

For example:

ByType automatic injection @autowired (Master)

You need to use the @AutoWired annotation on the reference property, which defaults to auto-assemble beans by type.

When property injection is done using this annotation, there is no need for setters in the class. Of course, if the property has a setter, you can add it to the setter.

For example:

ByName automatically injected @autowired with @Qualifier

The @autowired and @Qualifier annotations need to be used in conjunction with the reference attribute. The value attribute of @Qualifier is used to specify the ID value of the Bean to be matched. Class, and can be added to a set method.

For example:

The @autowired attribute also has a required value, which defaults to true to terminate the program if the match fails. If the value is set to false, the match fails and is ignored. The value of the unmatched property is null.

JDK annotation @resource automatic injection

Spring provides support for the @Resource annotation in the JDK. The @Resource annotation can match beans either by name or by type. The default is by name injection. JDK version 6 or later is required to use this note. @resource can be on properties or set methods.

(1) byType injects a reference type attribute

If the @resource annotation does not have any parameters, the bean is injected by name by default. If the bean cannot be injected by name, the bean will be injected by type.

For example:

(2) byName injects a reference type attribute

The @Resource annotation specifies its name attribute, and the value of name is the ID of the Bean that is matched by name.

For example:

Annotations versus XML

Note advantages are:

  • convenient
  • intuitive
  • Efficient (less code, less complex than writing configuration files).

The downside is also obvious: hardcoded into Java code, the changes require recompiling the code.

The advantages of XML are:

  • Configuration and code are separate
  • Making changes in THE XML, without compiling the code, simply restarts the server to load the new configuration. The downside of XML is that it is cumbersome to write, inefficient, and overly complex for large projects.

\ \ \ \ \ \ \

Three things to watch ❤️

If you find this article helpful, I’d like to invite you to do three small favors for me:

1. Like, forward, with your “like and comment”, is the power of my creation.

2. Follow the public account “Wish heaven has no BUG” and share original knowledge from time to time. Also look forward to the follow-up article ing

3. Reply [Learning] scan the code to obtain the learning materials package