Spring Dependency Injection

Source: Internet
Author: User

First, Spring introduction

1.Spring simplifies Java development

The Spring framework is an application framework that is generally semi-finished, and we can focus on the business logic without having to implement the architecture, infrastructure, and common functional components of each project on a framework basis. Therefore, learning the structure and principles of the spring framework in terms of architecture and patterns is of great help to our understanding of architecture and module level. The purpose of the Spring Framework (reference 1) is to simplify Java development, with the following main tools:

(1) Architecture decoupling: Managing Type Dependencies through Di (dependency injection), separating concerns through AOP, and reducing duplication of code.

(2) The design of a wide range of dip (dependency inversion) and ISP (interface isolation) and other principles and facade (appearance) and other modes: provide a simplified calling interface and encapsulate a number of excellent third-party components.

(3) Use annotations at the language level: Simplify application configuration with configuration files and annotation (refer to. NET Attribute).

Architecture and modules for the 2.Spring framework:

The schema of the Spring framework itself is typically loosely layered, with the outer layer referencing all the inner layers on demand, and the inner layer not referencing the outer layers. The basic components of spring are as follows:

As can be seen, the starting module only from Core\beans\aop\context Four components, later added Context-support "1.2" extension module, expression "3.0" extension Module and Beans-groovy "4.0" Extension module.

Based on the above modules, the spring is built-in and encapsulates a multitude of practical general-purpose components, the main components:

As you can see, SPRING-OXM, Spring-jdbc, and Spring-web are the cores of many module dependencies, and SPRING-OXM provides mapping support for object and XML.

Second, the basic knowledge

The 1.dip:dip (dependency inversion principle) is the core of Di (Dependency injection) (ref. 2).

(1) High-rise modules should not be dependent on low-level modules. Both should be dependent on abstraction.

(2) Abstraction should not depend on detail. The details should depend on abstraction.

The word is: the reference to the specific class is converted into a reference to its interface, the specific class only refers to the interface (reference = = Dependency, interface = = Interface or abstract class). In fact, when we invoke a specific class, we are only concerned with the API provided by it, not the implementation, and the dip is guaranteed to be decoupled by technical means during the design and refactoring phases.

2.di:di (Dependency injection) lets us not write factory code to manage interfaces and implement class mappings, object creation, and lifecycle management.

(1) Interface injection: must implement a specific interface to be able, intrusive too strong, now no one cares about and use.

(2) constructor injection: dependencies are reflected on the parameters of the constructor.

(3) Attribute injection: Dependency is reflected on the attribute.

Since the type can be registered as its own compatible type when implemented, dependency injection can replace the new instantiation object directly, so understanding and using the dependency Injection tool is better than not using or writing the factory. The dependency Injection tool will certainly be implemented as an object factory that supports different configurations and different lifecycles, but even without a set of APIs to add dependency inversion rules, it does not mean that we are replacing it with new alternatives. Just as the mapping tool can be arbitrarily mapped when implemented, but instead of replacing the assignment, it is used to deal with mappings between objects with actual correspondence, such as domain entities and view models.

(1) Dependency configuration: Dependency configuration is the basis for a dependency injection implementation. The Dependency Injection tool supports at least code configuration and file configuration. In Java, configuration can be simplified through annotation (. Net via attribute).

(2) Object factory: Returns one or more objects according to the configuration. This is the core feature.

(3) Lifecycle management: At least 4 levels of support are generally available: scopes, Singleton, threads, HTTP request scopes.

Most of the dependency injection tools, which support the dependency inversion principle, implement more functions on technical means, such as compatible conversions of types, naming dependencies, passing objects directly to the configuration, and so on.

Third, spring Dependency injection

Beans in spring is pojo (. Net poco), beans in spring is pojo,bean in spring is pojo, important things to say 3 times. You can simply think of a bean as an object.

The core of spring dependency injection is beanfactory and beandefinition. Corresponding to the concept of object factory and dependent configuration respectively. Although we typically use the ApplicationContext implementation class, ApplicationContext only encapsulates and extends the functionality of Beanfactory.

While XML configuration is a feature that supports early, powerful, and easy modification in spring Dependency injection, XML configuration is just one way that spring relies on injected read configurations. The core of spring dependency injection is the Beandefinition interface, no matter what configuration is supported and will be supported in the past, present and future. People who have experience using beandefinition through code may have been aware of this for a long time: various configurations will eventually be mapped to beandefinition. So we should use the appropriate configuration as needed, and don't take the minutiae as the core, at least whatever. NET or Java, dependency inversion, Object factory, life cycle and other concepts are universal, mastered these core concepts, then to learn the specific class library, will be more effective. ApplicationContext's implementation class Annotationconfigwebapplicationcontext with annotation annotations and generics has already provided a much simpler way to configure. As shown in the following code, the current spring dependency injection is already used very close to. NET usage.

Now let's focus on Annotationconfigapplicationcontext and Annotationconfigwebapplicationcontext. These two implementation classes are at the core of implementing a no-XML configuration.

1.Java General Applications:

(1) Dependency Injection code:

View Code

(2) interface and implementation code:

View Code

As we can see from the code, there is no need for a configuration file, no strings to be used, and no side effects on the interface class.

2.Java Web application:

(1) Dependency Injection code:

View Code

(2) Call in JSP (interface and implementation code ibid.):

View Code

With the addition of generics and annotations in Java and the updating of versions, Spring contains numerous applicationcontext, from the most basic classpathxmlapplicationcontext, Filesystemxmlapplicationcontext, Xmlwebapplicationcontext and other realization, and gradually with the times to add Genericwebapplicationcontext "1.2", Xmlportletapplicationcontext "2.0", Resourceadapterapplicationcontext "2.5", Genericxmlapplicationcontext "3.0", " Annotationconfigwebapplicationcontext ", Genericgroovyapplicationcontext" 4.0 ", Groovywebapplicationcontext" 4.1 ". Reading the spring source code is one of the best ways to learn, but if you just want to copy a Pom.xml+applicationcontext.xml+classpathxmlapplicationcontext call code, it's another matter.

Iv. key points of spring dependency injection

Hierarchical structure of 1.BeanFactory

Beanfactory is the core of spring's dependency injection, and its design mainly adopts ISP (interface isolation principle), which ensures the cohesion of single interface and ensures the simplicity of the whole system through multi-level interface inheritance. The core of our concern here is defaultlistablebeanfactory.

To see the Xmlbeanfactory code, you can see that xmlbeanfactory just loaded the beandefinition configuration through Xmlbeandefinitionreader, The Xmlbeandefinitionreader is responsible for parsing the configuration to beandefinition. Defaultlistablebeanfactory is a true implementation class that defines a beandefinitionmap list of type map<string and beandefinition> for storing dependent configurations.

Hierarchical structure of 2.BeanDefinitionReader:

In addition to the xmlbeandefinitionreader mentioned above, Beandefinitionreader also has 2 implementations of class Propertiesbeandefinitionreader and Groovybeandefinitionreader, There are also 1 individually defined Annotatedbeandefinitionreader. ApplicationContext implementation class, some are fixed with these beandefinitionreader, some are not unbound beandefinitionreader, we can by hand collocation way, Paired with one or more beandefinitionreader.


Hierarchical structure of 3.ApplicationContext

There are too many implementations of ApplicationContext, but the core is to delegate the object factory function to Beanfactory's implementation class Defaultlistablebeanfactory, The parsing configuration is a beandefinitionreader of 4 related classes.

, a variety of applicationcontext have 2 inheritance branches.

(1) The implementation class of Abstractrefreshableapplicationcontext abstract class:

Abstractrefreshableapplicationcontext uses the Defaultlistablebeanfactory object in Refreshbeanfactory and passes it as a parameter to the Loadbeandefinitions method 。

Filesystemxmlapplicationcontext and Classpathxmlapplicationcontext are used when the base class Abstractxmlapplicationcontext implements the Loadbeandefinitions method The Xmlbeandefinitionreader.

Xmlwebapplicationcontext and Xmlportletapplicationcontext use Xmlbeandefinitionreader, Groovywebapplicationcontext is using the Groovybeandefinitionreader.

Annotationconfigwebapplicationcontext is using the Annotatedbeandefinitionreader.

(2) Genericapplicationcontext class and its subclasses:

Genericapplicationcontext is not bound to a specific beandefinitionreader, we can directly use the type instance as a construction parameter to Beandefinitionreader, Then manually call the Beandefinitionreader Loadbeandefinitions method. This means that we can use multiple beandefinitionreader.

Genericgroovyapplicationcontext and Genericxmlapplicationcontext used Groovybeandefinitionreader and Xmlbeandefinitionreader respectively. 。

Annotationconfigapplicationcontext is using the Annotatedbeandefinitionreader.

Resourceadapterapplicationcontext and Genericwebapplicationcontext, like the base class Genericapplicationcontext, have no binding-specific implementations.

Spring's dependency injection has the concept of object factory and dependent configuration, but its dependency configuration is object-centric rather than type, and beandefinition directly corresponds to the object's information and its dependencies, which is evident when it is configured by code. Google Guice (ref. 3) is significantly better than spring in dependency inversion support and code configuration.

Reference

1.http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/overview.html

2.https://en.wikipedia.org/wiki/dependency_inversion_principle

3.http://www.ibm.com/developerworks/cn/java/j-guice.html

Spring Dependency Injection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.