Summary of Spring Interview Questions

1. What is Spring?

Spring is a lightweight IOC and AOP container framework. It is a set of frameworks that provide basic services for Java applications. The purpose is to simplify the development of enterprise applications. It makes developers only need to care about business needs. There are three common configuration methods: XML-based configuration, annotation-based configuration, and java-based configuration.

It mainly consists of the following modules:

Spring Core: core class library, providing IOC services;

Spring Context: provides framework-style Bean access, as well as enterprise-level functions (JNDI, scheduled tasks, etc.);

Spring AOP: AOP service;

Spring DAO: the abstraction of JDBC, which simplifies the handling of data access exceptions;

Spring ORM: support for existing ORM frameworks;

Spring Web: Provides basic web-oriented aggregate features, such as multi-party file uploads;

Spring MVC: Provides a Model-View-Controller implementation for web applications.

2. What are the advantages of Spring?

(1) Spring is a low-invasive design, and the pollution of the code is extremely low;

(2) Spring's DI mechanism transfers the dependencies between objects to the framework to reduce the coupling of components;

(3) Spring provides AOP technology to support centralized management of some common tasks, such as security, transactions, logs, permissions, etc., to provide better reuse.

(4) Spring's ORM and DAO provide good integration with third-party persistence layer frameworks and simplify the underlying database access.

(5) Spring does not force the application to completely depend on Spring, and developers can freely choose part or all of the Spring framework.

3. Spring's IOC understanding

(1) IOC is Inversion of Control, which refers to the transfer of the control right to create an object. In the past, the initiative and timing of creating an object was controlled by itself, but now this right is transferred to the Spring container, and the container is configured according to the configuration. files to create instances and manage dependencies between instances, loose coupling between objects and objects is also conducive to functional reuse. DI dependency injection and inversion of control are descriptions of the same concept from different perspectives, that is, the application relies on the IOC container to dynamically inject the external resources required by the object at runtime.

(2) The most intuitive expression is that the IOC makes the creation of the container no longer need to be new, and can be automatically generated by Spring, using the reflection mechanism of java, dynamically create and manage objects according to the configuration file at runtime, and call the objects. Methods.

(3) Three injection methods of Spring IOC: constructor injection, setter injection, and annotation injection.

While IOC keeps cooperating components loosely coupled, AOP becomes a reusable functional component that allows you to separate out functionality across all layers of your application.

4. Spring's AOP understanding

OOP is object-oriented, allowing developers to define vertical relationships, but it is not suitable for defining horizontal relationships, resulting in a lot of code duplication, which is not conducive to the reuse of various modules.

AOP, commonly known as aspect-oriented, as a supplement to object-oriented, is used to abstract and encapsulate public behaviors and logic that have nothing to do with business but affect multiple objects into a reusable module. This module Named as Aspect, it reduces the repetitive code in the system, reduces the coupling between modules, and improves the maintainability of the system. It can be used for authorization authentication, logging, and transaction processing.

The key to AOP implementation lies in the proxy mode. AOP proxies are mainly divided into static proxies and dynamic proxies. Static proxies are represented by AspectJ; dynamic proxies are represented by Spring AOP.

(1) AspectJ is an enhancement of static proxy. The so-called static proxy means that the AOP framework will generate AOP proxy classes during the compilation phase, so it is also called compile-time enhancement. It will weave AspectJ (aspect) into java bytes during the compilation phase. In the code, the runtime is the enhanced AOP object.

(2) The dynamic proxy used by Spring AOP, the so-called dynamic proxy means that the AOP framework does not modify the bytecode, but temporarily generates an AOP object for the method in the memory each time it runs. This AOP object contains the target object. All methods of , and enhanced processing at a specific pointcut, and callback methods of the original object.

There are two main ways of dynamic proxy of Spring AOP, JDK dynamic proxy and CGLIB dynamic proxy:

    ① JDK dynamic proxy only provides the proxy of the interface, and does not support the proxy of the class. The core InvocationHandler interface and the Proxy class, InvocationHandler invokes the code in the target class through the invoke() method reflection, and dynamically weaves the cross-cutting logic and business together; then, the Proxy uses the InvocationHandler to dynamically create an instance that conforms to a certain interface, generating A proxy object for the target class.

    ② If the proxy class does not implement the InvocationHandler interface, Spring AOP will choose to use CGLIB to dynamically proxy the target class. CGLIB (Code Generation Library) is a code-generating class library that can dynamically generate a subclass object of a specified class at runtime, and override specific methods and add enhanced code to implement AOP. CGLIB is a dynamic proxy through inheritance, so if a class is marked as final, it cannot use CGLIB as a dynamic proxy.

(3) The difference between static proxy and dynamic proxy is that the timing of generating AOP proxy objects is different. Relatively speaking, the static proxy method of AspectJ has better performance, but AspectJ requires a specific compiler for processing, while Spring AOP does not require specific compilation. processor processing.

InvocationHandler的invoke(Object proxy,Method,Object[] args):

proxy is the final generated proxy instance;

method is a specific method of the proxy target instance;

args is the specific input parameters of a method of the proxy target instance, which is used when the method is called by reflection.

5. What is the difference between BeanFactory and ApplicationContext?

BeanFactory and ApplicationContext are the two core interfaces of Spring, and both can be used as Spring containers. Where ApplicationContext is a sub-interface of BeanFactory.

(1) BeanFactory: It is the bottom-level interface in Spring. It contains definitions of various beans, reads bean configuration files, manages the loading and instantiation of beans, controls the life cycle of beans, and maintains dependencies between beans. As a derivation of BeanFactory, the ApplicationContext interface provides more complete framework functions in addition to the functions of BeanFactory:

    ① Inherit MessageSource, support internationalization

    ② Unified resource file access method.

    ③ Provide the event of registering the bean in the listener.

    ④ Load multiple configuration files at the same time.

    ⑤ Load multiple (inherited) contexts, so that each context focuses on a specific layer, such as the web layer of the application.

(2) The loading timing is different

    ① BeanFactory uses the form of verbal loading to inject beans, that is, only when a bean is used (the getBean() method is called), the bean is loaded and instantiated. This way we can't find some existing Spring configuration issues. If a property of the Bean is not injected, after the BeanFactory is loaded, an exception will be thrown until the getBean method is called for the first time.

    ② ApplicationContext, which creates all beans at one time when the container starts. In this way, when the container starts, we can find configuration errors in Spring, which is helpful to check whether the dependent properties are injected. Preloading all single instance beans after ApplicationContext starts, by preloading single instance beans ensures that when you need them, you don't have to wait because they are already created.

    ③ Compared with the basic BeanFactory, the only disadvantage of ApplicationContext is that it takes up memory space. When there are many application configuration beans, the program starts slowly.

(3) BeanFactory is usually created programmatically, and ApplicationContext can also be created declaratively, such as using ContextLoader.

(4) Both BeanFactory and ApplicationContext support the use of BeanPostProcessor and BeanFactoryPostProcessor, but the difference between the two is that BeanFactory needs to be registered manually, while ApplicationContext is automatically registered.

6. Please explain the life cycle of Spring Bean?

First, let's talk about the life cycle of Servlet: instantiate, initialize init, receive request service, destroy destroy;

The Bean declaration cycle in the Spring context is also similar, as follows:

(1) Instantiate Bean

For the BeanFactory container, when the user requests an uninitialized bean from the container, or when the bean needs to be injected with another uninitialized dependency, the container will call createBean for instantiation.

For the ApplicationContext container, when the container is started, all beans are instantiated by obtaining the information in the BeanDefinition object.

(2) Set object properties (dependency injection)

The instantiated object is encapsulated in the BeanWrapper object, and then Spring completes dependency injection according to the information in the BeanDefinition and the interface for setting properties provided by the BeanWrapper.

(3) Handling the Aware interface

Spring will detect whether the object implements the xxxAware interface, and inject the relevant xxxAware instance into the Bean;

    ① If the Bean has implemented the BeanNameAware interface, the setBeanName(String beanId) method implemented by it will be called, and the id value of the Bean in the Spring configuration file is passed here;

    ② If the Bean has implemented the BeanFatoryAware interface, the setBeanFactory() method implemented by it will be called, and the Spring factory itself will be passed;

    ③ If the bean has implemented the ApplicationContextAware interface, it will call the setApplicationContext(ApplicationContext) method it implements and pass in the Spring context;

(4)BeanPostProcessor

If you want to do some custom processing on the bean, you can make the bean implement the BeanPostProcessor interface, which will call the postProcessBeforeInitialization(Object obj, String s) method.

(5)InitializingBean 与 init-method

If a bean is configured with the init-method attribute in the Spring configuration file, its configured initialization method will be called automatically.

(6) If the Bean implements the BeanPostProcessor interface, the postProcessAfterInitialization(Object obj, String s) method will be called; since this method is called at the end of the Bean initialization, it can be applied to memory or caching technology;

(7)DisposableBean

When the Bean is no longer needed, it will go through the cleanup phase. If the Bean implements the DisposableBean interface, the destroy() method it implements will be called;

(8)destroy-method

Finally, if the destroy-method attribute is configured in the Spring configuration of this bean, its configured destroy method will be called automatically.

7. Explain the scope of several beans supported by Spring

The beans in the Spring container can be divided into 5 scopes:

(1) singleton: By default, each container has only one instance of a bean, and the singleton mode is maintained by the BeanFactory itself;

(2) prototype: provide an instance for each bean request;

(3) request: An instance is created for each network request. After the request is completed, the bean will be invalidated and recycled by the garbage collector;

(4) Session: Similar to the request scope, ensure that there is an instance of a bean in each session. After the session expires, the bean will become invalid.

(5) global-session: global scope, global-session is related to Portlet application. When your application is deployed to work in a portlet container, it contains many portlets. If you want to declare a global storage variable shared by all portlets, then this global variable needs to be stored in the global-session. The global scope has the same effect as the session scope in the servlet.

Portlets are Java-based web components managed by the portlet container, which processes requests and generates dynamic content.

Use portlets as pluggable user interface components to provide the presentation layer of the information system.

As the next step in web application programming with servlets, portlets enable modularity and user centralization of web applications.

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

The Spring framework does not perform 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 service and dao), 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. The most obvious solution is to change the scope of the polymorphic bean from singleton to prototype.

9. How does Spring handle thread concurrency?

In general, only stateless beans can be shared in a multi-threaded environment. In Spring, most beans can be declared as singleton scopes, because Spring uses ThreadLocal to process non-thread-safe states in some beans. Address thread safety issues.

Both ThreadLocal and thread synchronization mechanisms are designed to solve the access conflict problem of the same variable in multiple threads. The synchronization mechanism adopts the method of "time for space", only one variable is provided. Different threads need to acquire locks before accessing, and threads that do not acquire locks need to queue.

ThreadLocal will provide each thread with an independent copy of the variable, thereby isolating the access conflict of multiple threads to the data. Since each thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe shared objects. When writing multi-threaded code, unsafe variables can be encapsulated into ThreadLocal.

10. Spring's autowiring

There are 5 types of autowiring in Spring framework xml configuration:

(1) no: The default method is not to perform automatic assembly, and to configure the bean through the manual ref attribute.

(2) byName: Autowire by the name of the bean. If the property of a bean is the same as the name of another bean, autowire is performed.

(3) byType: Automatic assembly through the data type of the parameter.

(4) constructor: Use the constructor for assembly, and the parameters of the constructor are assembled through byType.

(5) autodetect: Automatic detection, if there is a constructor, it is automatically assembled by construct, otherwise it is automatically assembled by byType.

Annotation-based approach:

Use the @Autowired annotation to autowire the specified bean. Before using the @Autowired annotation, it needs to be configured in the Spring configuration file, <context:annotation-config />.

When spring IOC is started, the container automatically loads an AutowiredAnnotationBeanPostProcessor post-processor. When the container scans @Autowired, @Resource or @Inject, it will automatically find the required bean in the IOC container and assemble the properties of the object. When using @Autowired, first query the container for the bean of the corresponding type:

If the query result is exactly one, the bean is assembled to the data specified by @Autowired;

If there is more than one result of the query, then @Autowired will look up by name;

If the result of the above lookup is empty, an exception will be thrown. The solution is to use required=false.

@Autowired can be used in constructors, member variables, setter methods

Difference between @Autowired and @Resource?

(1) @Autowired is injected according to type assembly by default. By default, it requires that the dependent object must exist (required=false can be set).

(2) @Source assembles the injection according to the name by default, and assembles the injection according to the type only when no bean matching the name is found.

11. What design patterns are used in the Spring framework?

(1) Singleton mode: Bean defaults to singleton mode, singleton.

(2) Factory pattern: BeanFactory is the embodiment of the simple factory pattern, which is used to create an instance of an object.

(3) Proxy mode: Spring's AOP function uses JDK's dynamic proxy and CGLIB bytecode generation technology.

(4) Template method: used to solve the problem of code duplication, such as TestTemplate, JmsTemplate, JpaTemplate.

(5) Observer mode: Define a one-to-many dependency relationship. When the state of an object changes, all objects that depend on it will be notified and passively updated, such as the implementation of listener in Spring --> ApplicationListener.

{{o.name}}
{{m.name}}

Guess you like

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