Inversion of Control and Dependency Injection

Inversion of Control and Dependency Injection

 

Inversion of Control (Ioc)

The application itself is not responsible for the creation and maintenance of dependent objects, and the creation and maintenance of dependent objects are handled by the external container. In this way, the control right is transferred from the application to the external container, and the transfer of control right is the so-called reversal.

 

Dependency Injection

At runtime, there are external containers that dynamically inject dependent objects into components (constructors and setters)

 

 

Three ways of dependency injection

1. settter method injection

2. Constructor injection

3. Use @autowire or @resource annotation for injection. (most common method)

 

 

Three ways to assemble beans

1. xml configuration file

2. Notes

3. Java class configuration

 

 

bean scope

 

1. singleton : When the scope of a bean is singleton, there will only be one shared bean instance in the Spring IoC container, and all requests to the bean will only return the same bean as long as the id matches the bean definition. instance.

 

2. prototype : A bean definition corresponds to multiple object instances. A prototype-scoped bean causes a new bean instance to be created each time that bean is requested (either by injecting it into another bean, or by calling the container's getBean() method programmatically).

 

3. request : In an HTTP request, a bean definition corresponds to an instance; that is, each HTTP request will have its own bean instance, which is created according to a bean definition. This scope is only valid in the context of a web-based Spring ApplicationContext.

 

4. Session : In an HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the context of a web-based Spring ApplicationContext.

 

5. global session : In a global HTTP Session, a bean definition corresponds to an instance.

 

The setting method is as follows:

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl" scope="singleton">

 

 

Are singleton beans in spring framework thread safe?

no

 

The Spring framework does not do any multi-threaded encapsulation of singleton beans. The thread safety and concurrency issues of singleton beans need to be solved by developers themselves. But in fact, most Spring beans do not have mutable state (such as View and DAO classes), so Spring's singleton beans are thread-safe to some extent. If your beans have multiple states (such as View Model objects), you need to ensure thread safety by yourself.

 

How to ensure thread safety?

lock

 

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326493567&siteId=291194637