This is the 16th day of my participation in the August Text Challenge.More challenges in August

Following the previous chapter of Spring IoC inversion of control, the main contents of this paper are as follows:

  • The Spring assembly Bean
  • The Spring XML injection
  • Annotation-based DI dependency injection in Spring

The Spring assembly Bean

Example: The beanAssemble project

Assembly of beans, that is, creation of Bean objects. Assembly of beans is the process by which the container creates Bean objects as required by the code and then passes them to the code.

Default assembly mode

The code gets the specified Bean instance from the container via getBean(), which first calls the Bean class’s no-argument constructor to create a null-valued instance object.

For example:

The scope of the Bean in the container

When you create a Bean instance through the Spring container, you can not only instantiate the Bean, but also specify a specific scope for the Bean through the Scope property. Spring supports five scopes.

● Singleton: Singleton mode. That is, beans defined using singleton will be singletons with only one instance in the entire Spring container. The default is singleton.

I’m a prototype. That is, every time the same instance is retrieved using the getBean method, it is a new instance.

● Request: For each HTTP request, a different Bean instance will be generated.

● Session: For each different HTTP session, a different Bean instance is generated.

Note:

● This scope is valid only when Spring is used in Web applications for the value request and session of scope.

● For a singleton with scope as singleton, the Bean is assembled when the container is created.

● For the prototype pattern with scope of Prototype, the Bean instance is assembled when the Bean instance is used in the code.

For example:

The life of a custom Bean

You can customize the Bean’s life behavior after initialization or before destruction.

For example:

First, these methods need to be defined in advance in the Bean class: public void methods with arbitrary method names.

Second, add the following attributes to the tag of the configuration file:

Init-method: specifies the method name of the initialization method

Destroy-method: specifies the method name of the destroy method

Note that to see the result of the destroy-method execution of the Bean, two conditions need to be met:

● Beans are singletons, or singletons

● Make sure the container is closed. The interface ApplicationContext does not have a close() method, but its implementation class does. Therefore, you can either force the ApplicationContext into an implementation-class object, or create an implementation-class object.

The Spring XML injection

Example: project DI-XML

Injection of classification

After the bean instance creates a null-valued object by calling the no-argument constructor, 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 value injection and construct injection.

Set value injection

Set value injection means 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.

For example:

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, labels can be used in addition to the ref attribute of the label.

2. Structural injection

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.

For example:

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.

Property injection with collection properties

Example: DI03 package

● Inject values into arrays

● Inject values into List

 

● Inject values for Set

● Inject values into Map

● Inject values for Properties

● Injection of complex collection properties

Add new properties to the MyCollections class

In the container configuration file injection mode:

Automatic injection for reference type attributes

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:

  1. ByName: automatic injection byName
  2. ByType: automatic injection byType

1. Automatic injection byName

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.

1. Configuration files for equal relationships

Split the configuration files into multiple configuration files of equal status, and define the paths of all configuration files as a String array, which appears as container initialization parameters. It will match the container constructor with the mutable arguments.

Configuration files are parallel, regardless of primary or secondary.

For example:

2. Contain the configuration file of the relationship

Each configuration file contains a master file, which imports other subfiles. In Java code, you only need to initialize the container using the total configuration file.

For example:

Wildcard * may also be used. However, the parent configuration file name is not required to match the format, otherwise a 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 dependency injection in Spring

Example: di-Annotation project

Using annotations for DI eliminates the need to declare bean instances in the Spring configuration file. To use annotations in Spring, you need to make some changes to the existing Spring runtime environment to complete the following three steps.

1, import the AOP Jar package. The backend implementation of annotations uses AOP programming.

2. You need to change the header of the configuration file, that is, add corresponding constraints.

The constraint is in the %SPRING_HOME%\docs\spring-framework-reference\ HTML \ xsD-configuration.html file.

3. You need to configure a component scanner in the Spring configuration file to scan annotations in the specified base package.

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

(2) 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:

(3) 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

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 that are roughly equivalent to @Component:

● @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

These annotations, which are functionally equivalent to @Component, were created to extend them functionally in the future.

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

 

Simple type properties inject @Value

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 is automatically injected with @autoWired

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 as well.

For example:

ByName automatically injects @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. You don’t need a setter in the same class, you can add it to a setter.

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 is automatically injected

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. To use this annotation, the JDK must be version 6 or later.

@resource can be on properties or set methods.

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:

ByName injects the 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:

The life of a Bean is @postconstruct and @predestroy

Using @postconstruct on methods is equivalent to init-method. Using @predestroy on a method is equivalent to destroy-method.

For example:

Annotations versus XML

Note advantages are:

When convenient

Low 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.

● Configuration and code are separate

● Make changes in XML without compiling code, just restart 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.