3. Summary of Spring interview questions in the Java series

1. How to resolve circular references

A circular dependency is a circular nested reference of N classes.

1.1 Timing of Circular Dependency Occurrence

The initialization of a Spring singleton object is roughly divided into three steps:
1.createBeanInstance: instantiation, which is actually to call the object's construction method to instantiate the object
2.populateBean: filling properties, this step is mainly to fill in the dependency properties of multiple beans
3. initialzeBean: Initialization
The circular dependency mainly occurs in the first and second steps. That is, constructor circular dependency and field circular dependency

1.2 Constructor Circular Dependency

Throw BeanCurrentlylnCreationException

1.3 Singleton setter circular dependency

In order to solve the circular dependency problem of singletons, Spring uses a three-level cache
to complete the initialization of the bottom-level object first, and exposes the beans being created in advance through the three-level cache and the second-level cache, allowing other beans to complete the initialization first

/** 一级缓存:完成初始化的单例对象的cache **/
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);

/** 二级缓存:完成实例化但尚未填充属性初始化的单例对象的cache */
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);

/** 三级缓存:进入实例化阶段单例对象工厂的cache */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);

/**
bean 的获取过程:先从一级获取,失败再从二级、三级里面获取

创建中状态:是指对象已经 new 出来了但是所有的属性均为 null 等待被 init
*/

The process of detecting circular dependencies is as follows:

  • A needs B during the creation process, so A puts itself into the third-level cache to instantiate B
  • When B is instantiated, it is found that A is needed, so B first checks the first-level cache, if it is not checking the second-level cache, or not, it is checking the third-level cache, and found it!
    • Then put A in the third-level cache into the second-level cache, and delete A in the third-level cache
    • B is successfully initialized, and puts itself into the first-level cache (at this time, A in B is still in the creation state)
  • Then come back and create A. At this time, B has been created. Get B directly from the first-level cache, then complete the creation, and put yourself in the first-level cache
  • Such dependence solves the problem of circular dependence
	// 以上叙述的源码
	protected Object getSingleton(String beanName, boolean allowEarlyReference) {
    
    
		Object singletonObject = this.singletonObjects.get(beanName);
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
    
    
			synchronized (this.singletonObjects) {
    
    
				singletonObject = this.earlySingletonObjects.get(beanName);
				if (singletonObject == null && allowEarlyReference) {
    
    
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
    
    
						singletonObject = singletonFactory.getObject();
						this.earlySingletonObjects.put(beanName, singletonObject);
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		return singletonObject;
	}
1.4 Non-singleton circular dependency

Spring can't do dependency injection. Since Spring does not cache "prototype" multi-instance beans, it cannot expose a bean that is being created ahead of time.

2. What are the benefits of using the Spring framework?

Lightweight Spring is lightweight, the basic version is about 2M
Inversion of Control (IOC) Spring achieves loose coupling through inversion of control, and objects give dependencies instead of creating and finding dependent objects
Aspect-oriented (AOP) Spring Supports AOP programming, separates business logic from system services.
Container Spring manages the life cycle of objects in the application and configures the
MVC framework .
Transaction management Spring provides transaction management interfaces, ranging from local transactions to global transaction
exception handling . Spring provides APIs related to specific technologies. The exception is converted to a consistent unchecked exception

3. What modules does Spring consist of
spring-core  spring-beans  spring-context  spring-aop  spring-expression
spring-jdbc  spring-oxm    spring-tx       spring-web  spring-webmvc

4. What is the usual implementation of ApplicationContext?

ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
WebXmlApplicationContext

5. Explain the scope of several beans supported by Spring


There is only one corresponding bean instance prototype in a singleton container , and there are multiple instances of a bean definition. The following four are based on webApplicationContext request session globalSession application
under the web module



6. Are singleton beans in the Spring framework thread-safe?

no

7. Explain the bean life cycle in the Spring framework

  1. The Spring container reads the bean definition from the XML file and instantiates the bean
  2. Spring fills in all properties according to the bean definition
  3. If the bean implements the BeanNameAware interface, Spring passes the bean's Id to the setBeanName method
  4. If the bean implements the BeanFactoryAware interface, Spring passes the beanFactory to the setBeanFactory method
  5. If the bean implements the BeanPostProcessor interface, the postProcessorBeforeInitialization method will be called
  6. If the bean implements the InitializingBean interface, the afterPropertiesSet method is called; if the bean declares an initialization method, the initialization method is called
  7. If the bean implements the BeanPostProcessor interface, the postProcessorAfterInitialization method will be called
  8. If the bean implements the DisposableBean interface, the destroy method will be called

8. Why does the Spring team recommend using constructor injection instead of variable injection

The Java class will execute the constructor first, and then inject values ​​into the object annotated with @Autowired, and an error will be reported as follows:

@Autowired
private User user;
private String school;

public UserAccountServiceImpl(){
    
    
    this.school = user.getSchool();
}

Change to the recommended injection method:

private User user;
private String school;

@Autowired
public UserAccountServiceImpl(User user){
    
    
    this.user = user;
    this.school = user.getSchool();
}

Welcome to pay attention to the official account algorithm niche, this article is continuously updated

Guess you like

Origin blog.csdn.net/SJshenjian/article/details/130175790