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 based on 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:在一个全局的HTTP Session中,一个bean定义对应一个实例。

 

设置方法如下:

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

 

 

spring框架中的单例bean是线程安全的吗?

不是

 

Spring框架并没有对单例bean进行任何多线程的封装处理。关于单例bean的线程安全和并发问题需要开发者自行去搞定。但实际上,大部分的Spring bean并没有可变的状态(比如Serview类和DAO类),所以在某种程度上说Spring的单例bean是线程安全的。如果你的bean有多种状态的话(比如 View Model 对象),就需要自行保证线程安全。

 

应该怎么保证线程安全?

加锁

 

 

 

 

 

Guess you like

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