Spring series three: IoC and DI

Crystal curtain moving from the breeze, full frame rose a hospital incense.
Here Insert Picture Description

Outline

In software engineering, inversion of control ( IoC) is a design, coupled together between objects, automatically bound at runtime and compile time they need to refer to objects is uncertain. In this springtutorial, by way of example to understand ioc, and springthe difference between the dependency injection.

What is Inversion of Control (IOC)

In traditional object-oriented software design, the bottom of which is constituted by the N plurality of objects, through mutual cooperation among the various objects. And ultimately business processes. Inversion of Control is meant to create and look for dependent objects of control to the container, composite objects are implanted by the container, so between the object and the objects are loosely coupled, which would also facilitate the testing, which will help multiplexing function, more importantly, making the whole system very flexible structure of the program, although some people think that the use of the service Locator pattern can also provide inversion of control.

Use Inversion of Control as a design criterion has the following advantages:

  1. Perform a task and implementation are separated
  2. Each module is more concerned with their own designs.
  3. Module does not need to look at other systems, you can only rely.
  4. Upgrade module will not affect other modules

What is dependency injection (DI)

IoCIs a design paradigm, the goal is to provide more control over the various components of the application, so that these components can be done. Dependency injection is a pattern, for creating an object instance of the object dependency, at compile time and is not perceived. IoCIt depends on dependency injection, because it needs a mechanism to create and reference the components you need.

These two concepts collaborative work this way, allowing the preparation of more flexible, reusable code, and packaged. They are therefore an important object-oriented solutions for conceptual design.

How to achieve IoC

In object-oriented programming, there are several basic techniques may be implemented to control inversion. as follows:

  1. Using the factory pattern
  2. Use the Service Locator pattern
  3. Given any of the following types of dependency injection
  • Constructor injection
  • setter injection
  • Notes injection

Spring inversion control

org.springframework.beansAnd a org.springframework.contextpackage for the Springframework IoCprovides the underlying functionality of the container. BeanFactoryInterface provides more advanced configuration options, the ability to manage all objects. ApplicationContextInterfaces built on BeanFactorytop (which is a sub-interface), and added other features, such as with Springthe AOPeasier integration features, message resource handling (for internationalization), event propagation context and application-specific layer, for example, as Webused applicationsWebApplicationContext

BeanFactoryIt is the Spring IoCmain achievement of the container, and includes responsible management of the above Bean. BeanFactoryThe interface is Springimportant in the IoCcontainer interface.
Here Insert Picture Description

BeanFactoryInterface has many implementations. The most common BeanFactoryimplementation is XmlBeanFactoryclass. Other popular classes are XmlWebApplicationContext. According to beanthe definition, the plant will return different instances (objects included in Prototypethe design mode), or returns a single shared instance ( Singletondesign mode, wherein a single instance of the embodiment scope). Factory). Examples of the type of which depends on the return beanconfiguration of the plant: obtaining beaninstances APIis the same.

Before delving into dependency injection type, first determine springcreate the framework of beanthe way, because it will help to understand the next section.

How to create a bean instance in Spring

BeanThe definition can be seen as an object to create one or more actual configuration. Getting, the container looks named beanconfiguration, and use the beanconfiguration item definitions package to create (or acquire) an actual object.

Using Constructors

When you create using the constructor method bean, all ordinary class can be Springuse and compatible. In other words, you are creating a class does not need to implement any specific interfaces or encoded in a particular way. Only the specified beanclass is sufficient. Based XMLconfiguration items, such as may be specified beanclass:

<bean id="exampleBean" class = "cn.howtodoinjava.ExampleBean"/>

Using a static factory method

To create a definition using a static factory methods beanand specifying that contains static factory methods of class classattribute, need another named factory-methodproperty to specify the name of the factory method itself.

<bean id="exampleBean" class = "cn.howtodoinjava.ExampleBean" factory-method="createInstance"/>

SpringWant to be able to call this method and return an object available, after obtaining the object, the object will be deemed to be created by the constructor.

Example factory method

In a manner similar examples of the way through the static factory method, using an instance factory method to instantiate an existing container is calling beanthe factorymethod to create a new bean.

<bean id="myFactoryBean"  class="cn.howtodoinjava.MyFactoryBean">

<bean id="exampleBean"  factory-bean="myFactoryBean" factory-method="createInstance"></bean>

Spring's dependency injection

Dependency injection ( DI) basic principle behind this is that objects are only define their dependencies via constructor arguments, parameters or attributes factory method, these parameters are configured or from the factory method returns disposed on the object instance in the object instance of. Then, the work is actually injected into the container of these dependencies when creating the bean. I.e., by the IoChelp find the corresponding container object and dependent objects injection, not actively look for the object, so called inversion of control ( IoC).

setter injection

No parameters by calling a constructor or a static factory method without parameters to instantiate beanThereafter, beanthe calling settermethod may be implemented based on setterthe DI.

public class TestSetterDI {

DemoBean demoBean = null;

public void setDemoBean(DemoBean demoBean) {
    this.demoBean = demoBean;
  }
}

Constructor injection

Based constructor DIto achieve a constructor having a plurality of call parameters (each representing an object instance). Also, call the static factory method with specific parameters is constructed Beanalmost equivalent to the rest of the article will be considered similarly Parameter and static factory method constructor.

public class ConstructorDI {

DemoBean demoBean = null;

public TestSetterDI (DemoBean demoBean) {
    this.demoBean = demoBean;
  }
}

Notes injection

Notes injected only need to add member variables in the @Autowirenotes to

public class ConstructorDI {

@Autowire
private DemoBean demoBean;
  }
}

spring face questions

What is the difference between the components and services?

Is a set of software components, these components will be used by other applications, and will not make any changes. The so-called "no change" refers to the use of the application does not change the source code components, although they can change the components of the expansion of a component by component author permissible behavior.

Similar services and components for external applications. The main difference is that the components (such as the use of local jarfile, assembly, dllor introducing a source). Service through a remote synchronous or asynchronous interfaces (e.g., Webservice, messaging system, RPCor a socket) remotely.

DI and Service Locator pattern What's the difference?

The main benefit dependency injection device is that it allows the injection of appropriate services to achieve the environmental and usage. Injection is not the only method to break this dependency, another method is to use the service locator. The basic idea is to have the service of a locator object that knows how to have all service applications may be needed. Then, it scans all of these services, and stores them as a single case of the registry. When asked to provide the service implementation, the requester can query the registry and use the token for the appropriate implementation.

Typically, these registry is populated by some configuration files. The key difference is that, when using the locator service, for each user and services have dependencies on retainer. Locator can hide dependencies to other implementations, but still need to see the locator.

Which is better to use the service (a service locator or dependency injection)?

As already mentioned above, the key difference is that the use of locator service, each user will have a dependency on services locator. This means that you must learn more about the service locator in terms of inputs and outputs. So, in fact, be the determining factor which mode is selected.

If maintenance is simple and necessary registry information, you can use the service locator, or directly using dependency injection, because the users of its services are not aware

Which is better constructor injection or setter injection or comment?

Based on constructorthe injection will depend on the fixed order of injection; in this manner does not allow us to create a beancircular dependency between objects, such restrictions actually benefit utilizing constructor to inject - when you did not even notice the use of setterthe injection time , Springto solve the problem of circular dependencies;

Based setterinjection, only when the object is to be injected when it will help us to inject dependencies, and not just during initialization injected; on the other hand, if you use based on constructorinjection, CGLIBcan not create a proxy force you based interface agent or virtual no-argument constructor.

My preference is injected notes, this approach looks very good, fine short, high readability, no extra code, easy to maintain;

What is the BeanFactory?

BeanFactoryLike a factory class, which contains a series bean. BeanFactoryStored in its interior a plurality Beanof Beandefined and instantiated at the client requirements Bean.

BeanFactoryYou can create an association between instances of collaboration objects. This eliminates beanitself and beanconfiguration burden of the client. BeanFactoryAlso involved in beanthe life cycle, so as to call a custom initialization and destruction methods.

What is the ApplicationContext?

BeanFactory for simple applications, but to take advantage of Springthe full functionality of the framework, you may need to upgrade to Springa more advanced container that is application context. On the surface, the application context Beanfactory same, both loaded Beandefinition, Beanbound together and allocated according to the request Bean. But it also provides the following functions:

  • The solution text messages, including support for internationalization.
  • General method to load file resources.
  • For the beanevent registered listeners.

Common implementations of ApplicationContext What?

ApplicationContextThe three common implementation is:

  1. ClassPathXmlApplicationContext: It is located in the classpath from the XMLload context definition file, and the context definition considered to classpath resources. Using the code to load the application context from the application classpath.
    ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
    
    
  2. FileSystemXmlApplicationContext: It from the file system of the XMLloaded context definition file. Using the code to load the application context from the file system.
ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
  1. XmlWebApplicationContext: It is the WebXML file that contains the application loaded in context definition.

BeanFactory or ApplicationContext is best to use what?

BeanFactoryBasically just instantiated and configured Bean. ApplicationContextCan also do this, it provides a support infrastructure to support many enterprise-specific features, such as transaction and AOP.

Therefore, it is recommended to use ApplicationContext.

In this tutorial, we have springlearned iocand dithe difference between.


Here Insert Picture Description

??? attention to micro-channel public number java dry
from time to time information sharing Dry

Original link: the Spring - IoC Containers

Published 112 original articles · won praise 90 · Views 350,000 +

Guess you like

Origin blog.csdn.net/dandandeshangni/article/details/102626988