What is IOC in spring

IOC - inversion of control

In java development, IOC means that your designed class is controlled by the system, not within your class. IOC is a component design method that allows service consumers not to directly rely on service providers. It is a design principle to reduce the dependence between classes.

Di -- dependency injection

That is, the dependencies between components are determined by the container at run time. In image, that is, the container dynamically injects some dependencies into components. The goal of dependency injection is not to bring more functions to the software system, but to improve the probability of component reuse and build a flexible and scalable platform for the system. Through the dependency injection mechanism, we can specify the resources required by the target and complete our own business logic through simple configuration without any code, without caring where the specific resources come from and who implements them.

1: Control reversal:

Who controls who? Control what? Why is it called reversal (corresponding to the forward direction)? What aspects are reversed? Why do you need to reverse?

2: Dependency:

What is dependence (understood by nouns and verbs)? Who depends on whom? Why do you need to rely? What do you rely on?

3: Injection:

Who injects into who? Into what? Why inject?

4: Are dependency injection and control inversion the same concept?

5: Who are the participants?

6: What is IOC / di? What can you do? How do you do it? Where is it used?

It doesn't matter if you can't fully answer and understand it. Let's take a look at the evolution of the basic idea of IOC / Di, and then go back to answer these questions

IOC container

The simple understanding is that the software that implements the idea of IOC and provides object creation, object assembly and object life cycle management is IOC container.

IOC understanding

1: The application does not need to actively new objects; Instead, describe how the object should be created

IOC container helps you create, that is, passive instantiation;

2: Instead of actively assembling dependencies between objects, the application describes which services are needed

IOC container will help you assemble (i.e. be responsible for associating them together) and passively accept the assembly;

3: Take the initiative and become passive, reflecting the Hollywood Law: don't call us, we'll call you

4: Reflect the Dimitri rule (minimum knowledge principle): the application program does not know the specific implementation of dependency, but only knows the objects that need to provide a certain type of service (interface oriented programming); and it is loosely coupled. An object should know as little as possible about other objects and not talk to strangers (Implementation)

5: It is a component design method that makes service consumers not directly depend on service providers. It is a design principle to reduce the dependence between classes.

Ideas that need to be changed when using IOC / di container development

1: The application does not actively create objects, but describes how to create them.

2: Services are not assembled directly in the application code, but to describe which component needs which service, the container is responsible for assembling these services together.

In other words, all components are passive, and the container is responsible for component initialization and assembly. The application only realizes the function of the application after obtaining the corresponding components.

Remind me

IOC / DI is an idea, not a pure implementation technology. IOC is a common feature of the framework. It is only the transfer of control to the framework. Therefore, it cannot be called IOC container because IOC is implemented. Generally, IOC container with di function in addition to IOC is called IOC container, because the container needs to manage the component life cycle in addition to creating and assembling component relationships.

N tool preparation

1:Eclipse + Jdk6. 0. The eclipse used in the example is eclipse Java EE IDE for web developers, version: Helios service release 1

2:spring-framework-3.1. 0.M2-with-docs. zip

Build environment

1: Create a new project in eclipse, assuming the name is spring3test

2: Add the jar packages under dist in the distribution package to eclipse

3: Obtain the dependent packages required by spring according to the spring project. In the case of networking, run projects / build spring framework / build. Com through ant XML, you will automatically download the required jar package. The downloaded package is located under projects / ivy cache / repository.

4: For convenience, add these jar packages to eclipse as well

Development interface

Java code:

Development implementation class

Java code:

configuration file

1: Create a new file under SRC called ApplicationContext xml

2: Search for an example in the spring distribution package, such as using: projects \ org springframework. ApplicationContext under Context \ SRC \ test \ Java \ ORG \ springframework \ JMX XML, first delete all the configurations inside and leave the basic XML definition and root element. It is a DTD version and version 2.0.

It is recommended to use the schema version of spring 3, for example:

Java code:

4: Configure ApplicationContext The XML is as follows:

Java code:

Write the client as follows:

Java code:

Review and conclusion

1: In all the code (except the test code), there are no spring components.

2: The client code (here is our test code) is only interface oriented programming without knowing the specific name of the implementation class. At the same time, we can simply change the specific underlying implementation class by modifying the configuration file.

conclusion

1: First of all, our components do not need to implement the interface specified by the framework, so we can easily separate the components from spring without any modification (which is unimaginable in applications based on EJB rack Implementation).

2: Secondly, the dependencies between components are reduced, which greatly improves the reusability and maintainability of the code

3: Interface oriented programming

What is a bean in spring

In spring, the main bodies that make up the application and the objects managed by the spring IOC container are called beans. In short, beans are objects initialized, assembled and managed by the spring container. In addition, beans are nothing special (no different from other objects in the application). The bean definition and the dependencies between beans will be described by configuration metadata.

Why use the name bean

The motivation to use the name 'bean' instead of 'component' or 'object' stems from the spring framework itself (partly because it is relative to complex EJBs).

Spring's IOC container

org. springframework. beans. factory. Beanfactory is the actual representative of the spring IOC container, which is responsible for accommodating and managing beans.

The spring IOC container will read the configuration metadata; It instantiates, configures and assembles various objects in the application. Generally, we use simple and intuitive XML as the description format of configuration metadata. In the XML configuration metadata, we can define the beans that we want to manage through the spring IOC container.

IOC / DI is one of the core functions of spring. The reason why many functions provided by spring framework can be integrated is based on IOC

Beanfactory and ApplicationContext

org. springframework. Beans and org springframework. The context package is the foundation of the spring IOC container. Beanfactory provides an advanced configuration mechanism that makes it possible to manage objects of any nature. ApplicationContext is an extension of beanfactory, and its functions have been further enhanced, such as easier integration with spring AOP, message resource processing (internationalization processing), event passing and context implementation of various application layers (such as webapplicationcontext for Web Applications).

Confusion of interface selection

In practical applications, users sometimes don't know whether to choose beanfactory interface or ApplicationContext interface. However, generally, when building Java EE applications, ApplicationContext will be a better choice, because it not only provides all the features of beanfactory, but also allows more declarative ways to get the functions we want.

In short, beanfactory provides the configuration framework and basic functions, while ApplicationContext adds more functions to support the core content of the enterprise. ApplicationContext is completely extended from beanfactory, so the capabilities and behaviors of beanfactory are also applicable to ApplicationContext.

The instantiation of spring IOC container is very simple, as shown in the following example:

1: First:

Java code:

2: Second:

Java code:

3: Third:

Java code:

Read multiple configuration files

The first method:

In order to load multiple XML files and generate an ApplicationContext instance, the file path can be passed to the ApplicationContext constructor as a string array. The bean factory will read the bean definition from multiple files by calling the bean definition reader. Generally, the spring team prefers the above approach because each configuration will not be aware of their combination with other configuration files.

The second method:

Use one or more < import / > elements to load bean definitions from one or more other files. All < import / > elements must be placed before the < bean / > element to complete the import of bean definitions. Let's take an example:

Java code:

Common configuration contents in configuration file

Inside the IOC container, the bean definition is represented by the beandefinition object. The definition will contain the following information:

1: Fully qualified class name: This is usually the actual implementation class of the defined bean. If you instantiate a bean by calling the static factory method instead of using a regular constructor, the class name is actually the class name of the factory class.

2: Definitions of bean behavior, i.e. creation mode (prototype or singleton), automatic assembly mode, dependency check mode, initialization and destruction methods. These definitions will determine the behavior of beans in containers.

3: Constructor parameters and property values used to create bean instances. For example, using beans to define connection pools, you can specify the number of connections and the size limit of connection pools through properties or construction parameters.

4: The relationship between beans, that is, collaboration (or dependency).

Naming of beans

Each bean has one or more IDS (or called identifiers or names, which can be understood as one thing in terminology), and these IDS must be unique in the current IOC container.

Of course, you can also define a name for each bean, but it is not necessary. If it is not specified, the container will generate a unique name for it. The reason why the name attribute is not specified will be described later (for example, it is not required for internal beans).

Bean naming convention

The naming of beans adopts the standard Java Naming Convention, that is, the naming method of starting with lowercase letters and spacing between uppercase letters. Such as AccountManager, accountservice, etc.

Adopting a unified naming convention for beans will make the configuration easier to understand. And when using spring AOP, this simple naming method will benefit you a lot.

Alias of bean

A bean needs to provide multiple names, which can be specified through the alias attribute. An example is as follows:

How do containers instantiate beans

When XML is used to describe the configuration metadata, the type of instantiated object will be specified through the class attribute of the < bean / > element. The class attribute is mainly used for two purposes: in most cases, the container will directly call the constructor of the specified class through reflection to create beans (this is a bit similar to using the new operator in Java code); In rare cases, the container will call the static factory method of the class to create a bean instance, and the class attribute will be used to specify the class that actually has the static factory method (it doesn't matter whether the object type created by calling the static factory method is the current class or other classes).

Instantiate a bean with a constructor. The previous example is

Instantiate using static factory methods

When using static factory methods to create beans, in addition to specifying the class attribute, you also need to specify the factory method for creating bean instances through the factory method attribute. An example is as follows:

Instantiate using the instance factory method

Using this mechanism, the class attribute must be empty, and the factory bean attribute must be specified as the name of the bean containing the factory method in the current (or its ancestor) container. The factory method of the factory bean itself must be set through the factory method attribute, and this method cannot be static. An example is as follows:

Use container

In essence, beanfactory is just a high-level factory interface that maintains bean definitions and interdependencies. Use the getBean (string) method to get the bean instance; The method provided by beanfactory is extremely simple. N the basic principle behind dependency injection (DI) is that the dependencies between objects (i.e. other objects working together) can only be realized in the following ways: constructor parameters, factory method parameters, or setting properties for objects created by constructors or factory methods.

Therefore, the container's job is to inject those dependencies when creating beans. Compared with the three methods of autonomously controlling dependency injection, that is, the bean itself controls its instantiation, directly specifies dependencies in the constructor, or is similar to the service locator mode, the control is fundamentally reversed, which is the origin of the control inversion IOC name.

Application dependency injection (DI) benefits

After applying Di principles, the code will be clearer. Moreover, when the bean itself no longer worries about the dependencies between objects (and when and where to specify such dependencies and what the actual classes depend on), it will be easy to achieve a higher level of loose coupling. The basic implementation of dependency injection (DI) is

Di mainly has two injection methods, setter injection and constructor injection.

After invoking the non parametric constructor or instantiating the bean without the static factory method, the DI method based on setter can be implemented by calling the setter method of the bean. Examples are as follows:

Example -- Java class

Java code:

Example - configuration file

Example -- Java class

Java code:

Example - configuration file

Java code:

Default resolution method

Constructor parameters are matched by type. If the constructor parameter type in the bean definition is clear, the parameter order in the bean definition is the order of the corresponding constructor parameters

Constructor parameter type matching

You can use the type attribute to explicitly specify the simple type corresponding to the parameter. For example:

Java code:

Index of constructor parameters

Use the index attribute to explicitly specify the order in which constructor parameters appear. For example:

Java code:

The name of the constructor parameter

In spring 3, you can use the name of the constructor parameter to assign values directly. For example:

Java code:

Direct quantity (basic type, strings type, etc.)

The < value / > element specifies the value of an attribute or constructor parameter through a string. The JavaBean Attribute Editor will remove the string from Java. Net Lang. string type is converted to the actual property or parameter type. Example:

Java code:

Value can be used as a child element or attribute.

Nidref element

The Idref element is used to pass the IDs of other beans in the container to the < constructor Arg / > or < property / > element, and provides error verification function. The Idref element is similar to < value >, just passing a string to facilitate XML checking. Examples are as follows:

Java code:

Idref element continued

The main reason why the first form is preferable to the second is that the use of Idref tags allows the container to verify the existence of the referenced bean at deployment time. In the second method, the targetname attribute value passed to the client bean is not verified. Any input error will only be found when the client bean is actually instantiated (possibly accompanied by a fatal error). If the client bean is a prototype bean, this input error (and the resulting exception) may not be found long after the container is deployed.

If the referenced bean is in the same XML file and the bean name is the bean ID, you can use the local attribute, which allows the XML parser to validate the referenced bean when parsing the XML file. An example is as follows:

Reference other beans (collaborators) -- ref element

Although they are all references to another object, there are three different forms of pointing to another object through ID / name. Different forms will determine how to deal with scope and verification.

1: The first and most common form is to use the < ref / > tag to specify the target bean, for example:

2: The second form is to use the local attribute of ref to specify the target bean. It can use the XML parser to verify whether the referenced bean exists in the same file. Example:

3: The third way is to reference the bean in the parent container of the current container by using the parent attribute of ref, which is not commonly used. Example:

Java code:

Internal bean

The so-called internal bean refers to the bean defined by the < bean / > element in the < property / > or < constructor Arg / > element of a bean. The internal bean definition does not need to have an ID or name attribute. Even if the ID or name attribute value is specified, it will be ignored by the container. Example:

Java code:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>