Java - "Interview Questions - Spring"

Preamble

java - "Interview Questions - Basics"

Java - "Interview Questions - JVM"

Java——"Interview Questions - Multithreading & Concurrency"

Table of contents

Preamble

1. What is spring?

2. Why do you use the Spring framework in your project?

3. What is the difference between Autowired and Resource keywords?

4. There are several ways of dependency injection, and what are they?

5. Tell me what is Spring

6. Talk about your understanding of Spring MVC

7. What are the common annotations of SpringMVC?

8. Talk about your understanding of Spring's AOP

9. What is the difference between Spring AOP and AspectJ AOP?

In Spring AOP, what is the difference between concerns and crosscutting concerns?

What is a notification? What types are there?

10. Tell me about your understanding of Spring's IOC?

11. Explain the life cycle of spring beans

 12. Explain the scope of several beans supported by Spring?

13. How many ways does Spring inject beans based on xml?

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

15. Talk about the difference between ApplicationContext and BeanFactory in Spring

16. Is the singleton bean in the Spring framework thread-safe?

17. How does Spring solve circular dependencies?

18. Talk about the isolation level of the transaction

19. Talk about the communication level of the transaction

20. Spring transaction implementation

22. What are the three elements of business?

23. What is the essence of transaction annotation?


1. What is spring?

Spring is an open source development framework for java enterprise applications. Spring is mainly used to develop Java applications, but some extensions are aimed at
building web applications for the J2EE platform. The goal of the Spring Framework is to simplify Java enterprise application development and promote good programming habits through a POJO-based programming model.

2. Why do you use the Spring framework in your project?

If you ask this question, just talk about the benefits of the Spring framework. For example, Spring has the following characteristics:

  • Lightweight : Spring is lightweight, the basic version is about 2MB.
  • Inversion of Control : Spring achieves loose coupling through inversion of control, objects give their dependencies instead of creating or finding dependent objects.
  • Aspect-Oriented Programming (AOP) : Spring supports aspect-oriented programming and separates application business logic from system services.
  • Container : Spring contains and manages the lifecycle and configuration of objects in the application.
  • MVC framework : Spring's WEB framework is a well-designed framework and a good substitute for the Web framework.
  • Transaction management : Spring provides a persistent transaction management interface that can be extended from local transactions down to global transactions (JTA).
  • Exception handling : Spring provides a convenient API to convert specific technology-related exceptions (such as those thrown by JDBC, Hibernate or JDO) into consistent unchecked exceptions.

3. What is the difference between Autowired and Resource keywords?

 Both @Resource and @Autowired are used for bean injection. In fact, @Resource is not a Spring annotation. Its package is javax.annotation.Resource, which needs to be imported, but Spring supports the injection of this annotation.

1. Common ground

Both can be written on fields and setter methods. If both are written on the field, then there is no need to write the setter method.

2. Differences

(1)@Autowired

The annotations provided by @Autowired for Spring need to import the package
org.springframework.beans.factory.annotation.Autowired; only inject byType.

public class TestServiceImpl {
    // 下面两种@Autowired只要使用一种即可
    @Autowired
    private UserDao userDao; // 用于字段上

    @Autowired
    public void setUserDao(UserDao userDao) { // 用于属性的方法上
        this.userDao = userDao;
    }
}

The @Autowired annotation assembles dependent objects according to type (byType). By default, it requires that dependent objects must exist. If null values ​​are allowed, you can set its required attribute to false. If we want to assemble by name, we can use it in conjunction with the @Qualifier annotation. as follows:

public class TestServiceImpl {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;
}

(2)@Resource

@Resource is automatically injected by ByName by default, provided by J2EE, and the package javax.annotation.Resource needs to be imported. @Resource has two important attributes: name and type, and Spring resolves the name attribute of the @Resource annotation to the name of the bean, and the type attribute resolves to the type of the bean. Therefore, if the name attribute is used, the byName automatic injection strategy is used, and when the type attribute is used, the byType automatic injection strategy is used. If neither the name nor the type attribute is specified, the byName automatic injection strategy will be used through the reflection mechanism.

public class TestServiceImpl {
    // 下面两种@Resource只要使用一种即可
    @Resource(name = "userDao")
    private UserDao userDao; // 用于字段上

    @Resource(name = "userDao")
    public void setUserDao(UserDao userDao) { // 用于属性的setter方法上
        this.userDao = userDao;
    }
}

Note: It is best to put @Resource on the setter method, because this is more in line with the object-oriented thinking, and the properties are manipulated through set and get instead of directly.

@Resource assembly order:

① If both name and type are specified, the only matching bean is found from the Spring context for assembly, and an exception is thrown if it cannot be found.

② If the name is specified, the bean with the matching name (id) will be searched from the context for assembly, and an exception will be thrown if it cannot be found.

③If type is specified, find the only bean that matches similarly from the context for assembly, if it cannot find or find more than one, an exception will be thrown.

④ If neither name nor type is specified, it will be automatically assembled according to the byName method; if there is no match, it will fall back to an original type for matching, and if it matches, it will be automatically assembled.

The role of @Resource is equivalent to @Autowired, except that @Autowired is automatically injected according to byType.

4. There are several ways of dependency injection, and what are they?

1. Constructor injection

The dependent object is injected into the dependent object through the parameters of the constructor, and injected when the object is initialized.

Advantages: A usable object is available after object initialization is complete.

Disadvantages: When there are many objects to be injected, the constructor parameter list will be very long; not flexible enough. If there are multiple injection methods, and each method only needs to inject a few specified dependencies, then it is necessary to provide multiple overloaded constructors, which is troublesome.

Two, setter method injection

The IoC Service Provider injects the dependent object into the dependent class by calling the setter function provided by the member variable.

Pros: Flexible. Objects that are needed can be selectively injected.

Disadvantages: After the dependent object is initialized, it cannot be used because the dependent object has not been injected yet.

3. Interface injection

The dependent class must implement the specified interface, and then implement a function in the interface, which is used for dependency injection. The parameter of this function is the object to be injected.

Advantages: In interface injection, the name of the interface and the name of the function are not important, as long as the parameter of the function is the type of object to be injected.

Cons: The intrusive line is too strong and not recommended.

PS: What is an intrusive row? If class A wants to use a function provided by others, if in order to use this function, it needs to add additional code to its own class, which is intrusive.

5. Tell me 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 allows developers to only 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: Provide framework-style Bean access methods, as well as enterprise-level functions (JNDI, scheduled tasks, etc.);

Spring AOP: AOP service;

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

Spring ORM: support for existing ORM frameworks;

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

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

6. Talk about your understanding of Spring MVC

What is the MVC pattern

MVC: MVC is a design pattern

Schematic of MVC

 analyze:

M-Model model (complete business logic: composed of javaBean, service+dao+entity)

V-View view (for interface display jsp, html...)

C-Controller controller (receive request—>call model—>dispatch page according to result)

springMVC is an MVC open source framework, springMVC=struts2+spring, springMVC is equivalent to the integration of Struts2 plus sring, but there is a doubt here, what is the relationship between springMVC and spring? There is a good explanation for this on Baidu Encyclopedia: It means that springMVC is a follow-up product of spring. In fact, spring provides an MVC module for web applications on the basis of the original. SpringMVC can be simply understood as spring It is often said that springMVC and spring are seamlessly integrated on the Internet. In fact, springMVC is a sub-module of spring, so there is no need to integrate with spring at all.

working principle:

 1. The user sends a request to the front controller DispatcherServlet.

2. DispatcherServlet receives a request to call HandlerMapping processor mapper.

3. The processor mapper finds the specific processor (can be searched according to the xml configuration and annotation), generates the processor object and the processor interceptor (if there is one), and returns it to the DispatcherServlet.

4. DispatcherServlet calls HandlerAdapter processor adapter.

5. The HandlerAdapter calls a specific processor (Controller, also called a back-end controller) after adaptation.

6. After the execution of the Controller is completed, it returns to the ModelAndView.

7. HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet.

8. DispatcherServlet passes ModelAndView to ViewReslover view parser.

9. ViewReslover returns a specific View after parsing.

10. DispatcherServlet renders the view according to the View (that is, fills the model data into the view).

11. DispatcherServlet responds to the user.

Component Description:

The following components typically provide implementations using the framework:

DispatcherServlet: As a front-end controller, the center of the entire process control, control the execution of other components, unified scheduling, reduce the coupling between components, and improve the scalability of each component.

HandlerMapping: Implement different mapping methods by extending the processor mapper, such as: configuration file method, interface implementation method, annotation method, etc.

HandlAdapter: Support more types of processors by extending the processor adapter.

ViewResolver: By extending the view resolver, it supports more types of view resolution, such as: jsp, freemarker, pdf, excel, etc.

Components:

1. The front-end controller DispatcherServlet (no need for engineers to develop), provided by the framework Function : receive requests, respond to results, equivalent to forwarders, central processing units. With dispatcherServlet, the coupling between other components is reduced. When the user request arrives at the front controller, it is equivalent to c in the MVC mode. The dispatcherServlet is the center of the entire process control. It calls other components to process the user's request. The existence of the dispatcherServlet reduces the coupling between components.

2. Processor mapper HandlerMapping (no need for engineer development), provided by the framework : find Handler according to the requested url HandlerMapping is responsible for finding Handler or processor according to user request, springmvc provides different mappers to achieve different mapping methods, for example : Configuration file method, interface implementation method, annotation method, etc.

3. The role of the processor adapter HandlerAdapter: to execute the Handler according to specific rules (the rules required by the HandlerAdapter) to execute the processor through the HandlerAdapter. This is the application of the adapter mode, and more types of processors can be executed by extending the adapter.

4. Processor Handler (requires engineer development) Note: When writing Handler, follow the requirements of HandlerAdapter , so that the adapter can execute Handler correctly. Handler is the back-end controller following the DispatcherServlet front-end controller. Specific user requests are processed. Since Handlers are related to specific user business requests, engineers are generally required to develop Handlers according to business requirements.

5. View resolver View resolver (does not need to be developed by an engineer), provided by the framework Function : perform view resolution, and resolve it into a real view (view) according to the logical view name. View Resolver is responsible for generating the View view from the processing result. The view name is parsed into the physical view name, that is, the specific page address, and then the View view object is generated, and finally the View is rendered to display the processing results to the user through the page. The springmvc framework provides many View types, including: jstlView, freemarkerView, pdfView, etc. In general, it is necessary to display model data to users through page tags or page template technology, and engineers need to develop specific pages according to business needs.

6. View View (requires engineers to develop jsp...) View is an interface, and the implementation class supports different View types (jsp, freemarker, pdf...)

The specific process steps of the core architecture are as follows:

1. First, the user sends a request --> DispatcherServlet. After receiving the request, the front-end controller does not process it by itself, but entrusts it to other parsers for processing, as a unified access point for global process control;

2. DispatcherServlet——>HandlerMapping, HandlerMapping will map the request to a HandlerExecutionChain object (including a Handler processor (page controller) object, multiple HandlerInterceptor interceptors) objects, through this strategy mode, it is easy to add new mappings Strategy;

3. DispatcherServlet——>HandlerAdapter, HandlerAdapter will package the processor as an adapter to support multiple types of processors, that is, the application of the adapter design pattern, so that it is easy to support many types of processors;

4. HandlerAdapter ——> call the processor function processing method, HandlerAdapter will call the real processor function processing method according to the adaptation result, complete the function processing; and return a ModelAndView object (including model data, logical view name) ;

5. The logical view name of ModelAndView --> ViewResolver, ViewResolver will resolve the logical view name into a specific View. Through this strategy mode, it is easy to replace other view technologies;

6. View --> Rendering, View will render according to the incoming Model model data, the Model here is actually a Map data structure, so it is easy to support other view technologies;

7. Return control to DispatcherServlet, and DispatcherServlet returns a response to the user, and this process ends.

Seeing these steps, I believe that everyone feels very confused, which is normal, but here is mainly to let everyone understand several components in springMVC:

Front-end controller (DispatcherServlet): Receives requests and responds to results, which is equivalent to the CPU of a computer.

Processor Mapper (HandlerMapping): Find the processor according to the URL.

Processor (Handler): Programmers are required to write code to process logic.

Processor Adapter (HandlerAdapter): The processor will be packaged into an adapter, so that it can support multiple types of processors, analogous to a notebook adapter (adapter mode application).

View Resovler (ViewResovler): Perform view resolution, process the returned strings, and parse them into corresponding pages.

7. What are the common annotations of SpringMVC?

@RequestMapping: An annotation for processing request url mapping, which can be used on classes or methods. When used on a class, it means that all methods in the class that respond to requests use this address as the parent path.

@RequestBody: The annotation realizes receiving the json data of the http request and converting the json into a java object.

@ResponseBody: The annotation implementation converts the object returned by the conreoller method into a json object to respond to the client.

8. Talk about your understanding of Spring's AOP

AOP (Aspect-Oriented Programming, Aspect-Oriented Programming) can encapsulate the logic or responsibility (such as transaction processing, log management, permission control, etc.) , reduce the coupling between modules, and facilitate future scalability and maintainability.

Spring AOP is based on dynamic proxy. If the object to be proxied implements an interface, Spring AOP will use JDK dynamic proxy to create the proxy object; for objects that do not implement the interface, JDK dynamic proxy cannot be used, and instead Use CGlib dynamic proxy to generate a subclass of the proxy object as a proxy.

 Note: implements and extends in the figure. That is, one is the interface and the other is the implementation class.

Of course, AspectJ can also be used. AspectJ has been integrated in Spring AOP. AspectJ should be regarded as the most complete AOP framework in the Java ecosystem. After using AOP, we can abstract some common functions and use them directly where they are needed, which can greatly simplify the amount of code. We need to add new functions conveniently and improve the scalability of the system. AOP is used in scenarios such as log function, transaction management, and authority management.

As long as you mention AspectJ here, the interviewer is likely to continue to ask:

9. What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is a runtime enhancement, while AspectJ is a compile-time enhancement. Spring AOP is based on proxying (Proxying), while AspectJ is based on bytecode manipulation (Bytecode Manipulation).

Spring AOP has integrated AspectJ, and AspectJ should be regarded as the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simpler.

If we have fewer aspects, then the performance difference between the two is not big. However, when there are too many aspects, it is best to choose AspectJ, which is much faster than SpringAOP.

May continue to ask:

In Spring AOP, what is the difference between concerns and crosscutting concerns?

A concern is the behavior of a module in an application, and a concern may be defined as a function we want to achieve. A cross-cutting concern is a concern that is used throughout the application and affects the entire application, such as logging, security, and data transfer, functions that are required by almost every module of the application. So these are crosscutting concerns.

So what is a join point? A join point represents a location in an application where we can insert an AOP aspect, which is actually a location where the application executes Spring AOP.

What is the entry point? A pointcut is a join point or set of join points at which advice is to be executed. Pointcuts can be specified by expressions or matches.

What is a notification? What types are there?

Notification is an action to be done before or after the execution of the method. In fact, it is a code segment to be triggered by the Spring AOP framework when the program is executed.

Spring aspects can apply five types of advice:

  • before: Pre-advice, which is called before a method is executed.
  • after: Advice invoked after the method execution, regardless of whether the method execution was successful or not.
  • after-returning: Advice to be executed only after the method completes successfully.
  • after-throwing: Advice executed when the method exits with an exception thrown.
  • around: Advice called before and after method execution.

10. Tell me about your understanding of Spring's IOC?

(1) IOC is the inversion of control, which refers to the transfer of control over the creation of objects. In the past, the initiative and timing of creating objects were controlled by oneself, but now this power is transferred to the Spring container, and the container creates instances and manages the dependencies between instances according to the configuration files. Loose coupling between objects is also conducive to the reuse of functions. DI dependency injection and inversion of control are descriptions from different angles of the same concept, 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 IOC allows the creation of objects without going to new, which can be automatically produced by spring, using the reflection mechanism of java, dynamically creating objects and managing objects at runtime according to the configuration file, and calling the object's method.

(3) Spring's IOC has three injection methods: constructor injection, setter method injection, and injection based on annotations.

IoC keeps collaborating components loosely coupled, while AOP programming allows you to separate the functions throughout the application layers to form reusable functional components.

11. Explain the life cycle of spring beans

First, let’s talk about the life cycle of Servlet: instantiation, initial init, receiving request service, destroying destroy;

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

(1) Instantiate the bean:

For the BeanFactory container, when the client requests a bean that has not been initialized from the container, or needs to inject another dependency that has not been initialized when the bean is initialized, the container will call createBean for instantiation. For the ApplicationContext container, after the container starts, 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) Handle the Aware interface:

Next, 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, it will call the setBeanName(String beanId) method implemented by it, and the id value of the Bean in the Spring configuration file is passed here;

②If the Bean has implemented the BeanFactoryAware interface, it will call the setBeanFactory() method it implements, passing the Spring factory itself.

③If the Bean has implemented the ApplicationContextAware interface, it will call the setApplicationContext(ApplicationContext) method 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 the 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 cache technology;

After the above steps are completed, the Bean has been correctly created, and then the Bean can be used.

(7)DisposableBean:

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

(8)destroy-method:

Finally, if the destroy-method attribute is configured in the Bean's Spring configuration, its configured destruction method will be called automatically.

 12. Explain the scope of several beans supported by Spring?

Beans in the Spring container can be divided into 5 scopes:

(1) singleton: By default, there is only one bean instance in each container, and the singleton mode is maintained by BeanFactory itself.

(2) prototype: Provide an instance for each bean request.

(3) request: Create an instance for each network request. After the request is completed, the bean will fail and be recycled by the garbage collector.

(4) session: similar to the request scope, ensure that there is a bean instance in each session, and the bean will become invalid after the session expires.

(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 for all portlets, then this global variable needs to be stored in global-session. The global scope has the same effect as the session scope in Servlet.

13. How many ways does Spring inject beans based on xml?

(1) Set method injection;

(2) Constructor injection: ① Set the position of the parameter through index; ② Set the parameter type through type;

(3) Static factory injection;

(4) Instance factory;

Usually you can answer the first two, because many people are not very good at the latter two, so if you don’t know it, don’t say it, or it will be embarrassing if you don’t know it.

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

This is a relatively difficult topic. You not only need to return to the design pattern, but also know how each design pattern is used in Spring.

Simple factory pattern : BeanFactory in Spring is the embodiment of simple factory pattern. The Bean object is obtained by passing in a unique identifier, but whether to create it after passing in the parameters or before passing in the parameters depends on the specific situation.

Factory pattern : FactoryBean in Spring is a typical factory method pattern. The bean that implements the FactoryBean interface is a type of bean called factory. Its characteristic is that when spring uses getBean() to get the bean, it will automatically call the bean's getObject() method, so what is returned is not the factory bean, but the return value of the bean.getOjbect() method.

Singleton mode : The singleton modes used in spring are: scope="singleton", registered singleton mode, and beans are stored in Map. The bean name is used as the key, and the bean is used as the value.

Prototype mode : The prototype mode used in spring is: scope="prototype", each time a new instance is obtained by cloning, and the original instance object will not be affected when it is modified.

Iterator mode : There is a CompositeIterator in Spring that implements Iterator, Iterable interface and Iterator interface, both of which are iteration-related interfaces. It can be considered that if the Iterable interface is implemented, it means that an object can be iterated. The Iterator interface is equivalent to an iterator, and implementing the Iterator interface is equivalent to defining how the iterable object is iterated.

Proxy mode : The classic AOP in Spring is realized by using dynamic proxy, which is divided into JDK and CGlib dynamic proxy.

Adapter mode : AdvisorAdapter class in AOP in Spring, which has three implementations: MethodBeforAdviceAdapter, AfterReturningAdviceAdapter, ThrowsAdviceAdapter. Spring will use the corresponding Advice according to different AOP configurations. Unlike the strategy mode, a method can have multiple Advices at the same time. There are many springs that end with Adapter, and most of them are adapter patterns.

Observer pattern: Event and Listener in Spring. Spring event: ApplicationEvent, the abstract class inherits the EventObject class, and JDK suggests that all events should inherit from EventObject. Spring event listener: ApplicationListener, which inherits the EventListener interface, JDK suggests that all event listeners should inherit EventListener.

Template mode: org.springframework.jdbc.core.JdbcTemplate in Spring is a very classic application of template mode. The execute method inside defines the entire algorithm steps.

Responsibility chain mode : The doDispatch() method in DispatcherServlet obtains the HandlerExecutionChain that matches the request, and the processing of this.getHandler() method uses the responsibility chain mode.

Note: This is just a list of some design patterns. In fact, there are flyweight patterns, builder patterns, etc. used in it. The optional answer is mainly because you are afraid that if you answer the iterator mode, and then continue to ask you, if you don’t know what to ask, it will be embarrassing.

15. Talk about the difference between ApplicationContext and BeanFactory in Spring

Class Diagram

The package directory is different

spring-beans.jar 中 org.springframework.beans.factory.BeanFactory

spring-context.jar 中 org.springframework.context.ApplicationContext

globalization

BeanFactory does not support internationalization, because BeanFactory does not extend the MessageResource interface in Spring. On the contrary, since ApplicationContext extends the MessageResource interface, it has the capability of message processing (i18N).

Powerful event mechanism (Event)

Basically, when it comes to the design of events (Event), it is inseparable from the observer mode. The event mechanism of ApplicationContext is mainly provided through the two interfaces of ApplicationEvent and ApplicationListener, which is the same as the event mechanism in Java swing. That is, when an event is published in the ApplicationContext, all beans that extend the ApplicationListener will receive the event and process it accordingly.

Access to underlying resources

ApplicationContext extends the ResourceLoader (resource loader) interface, which can be used to load multiple Resources, while BeanFactory does not extend ResourceLoader.

Support for web applications

Unlike a BeanFactory that is usually created programmatically, an ApplicationContext can be created declaratively, eg using a ContextLoader.

Of course, you can also use one of the implementations of ApplicationContext to create an instance of ApplicationContext programmatically.

lazy loading

1. BeanFactroy uses lazy loading to inject beans, that is, only when a certain bean is used (call getBean()), the bean is loaded and instantiated. In this way, we cannot find some existing spring configuration problems. On the contrary, ApplicationContext creates all beans at once when the container starts. This way, when the container starts up, we can spot configuration errors in Spring.

2. Both BeanFactory and ApplicationContext support the use of BeanPostProcessor and BeanFactoryPostProcessor. The difference between the two is: BeanFactory needs to be registered manually, while ApplicationContext is registered automatically.

It can be seen that ApplicationContext inherits BeanFactory, and BeanFactory is a relatively primitive Factory in Spring, which does not support Spring plug-ins such as AOP and Web. And ApplicationContext not only contains all the functions of BeanFactory, but also supports various plug-ins of Spring, and also works in a frame-oriented way, as well as layering and implementing inheritance on the context.

BeanFactory is the infrastructure of the Spring framework, oriented to Spring itself; while ApplicationContext is oriented to developers using Spring, and it provides more practical application-oriented functions than BeanFactory. In almost all occasions, ApplicationContext can be used directly instead of the underlying BeanFactory.

Common container

The BeanFactory type has XmlBeanFactory, which can create corresponding Beans according to the content defined in the XML file.

Common containers of the ApplicationContext type are:

1. ClassPathXmlApplicationContext: read the context from the ClassPath XML configuration file and generate the context definition. The application context is obtained from program environment variables.

2. FileSystemXmlApplicationContext: The context is read from the XML configuration file in the file system.

3. XmlWebApplicationContext: The context read by the XML file of the Web application. For example, what we use in Spring MVC.

16. Is the singleton bean in the Spring framework thread-safe?

The Spring framework does not perform any multi-threaded encapsulation of singleton beans.

Regarding the thread safety and concurrency issues of singleton beans, developers need to solve them by themselves.

The thread safety issue of singletons is not what Spring should care about. What Spring should do is to provide the function of creating a single instance of Bean or multiple instances of Bean according to the configuration.

Of course, but in fact, most Spring beans have no mutable state, so to some extent Spring's singleton beans are thread-safe. If your Bean has multiple states, you need to ensure thread safety by yourself. The most obvious solution is to change the scope of polymorphic beans (Scope) from Singleton to Prototype.

17. How does Spring solve circular dependencies?

 The whole process is roughly as follows:

1. Firstly, A completes the first step of initialization and exposes itself in advance (exposure itself in advance through ObjectFactory). When initializing, he finds that he depends on object B. At this time, he will try to get(B). At this time, he finds that B has not yet been created;

2. Then B goes through the creation process. When B is initialized, it also finds that it depends on C, and C has not been created;

3. At this time, C starts the initialization process again, but finds that it depends on A during the initialization process, so it tries to get(A). At this time, since A has been added to the cache (usually added to the L3 cache singletonFactories), it is exposed in advance through the ObjectFactory, so the A object can be obtained through the ObjectFactory#getObject() method. C successfully completes the initialization after getting the A object, and then adds itself to the first-level cache;

4. Back to B, B can also get the C object to complete the initialization, and A can successfully get B to complete the initialization. At this point, the entire link has completed the initialization process.

Keywords: L3 cache, early exposure.

18. Talk about the isolation level of the transaction

Read Uncommitted: Allows dirty reads, that is, it is possible to read data modified by uncommitted transactions in other sessions

Read Committed: Only committed data can be read. Most databases such as Oracle are at this level by default (non-repeatable read)

Repeated Read: The queries in the same transaction are consistent at the beginning of the transaction, the default level of Mysql's InnoDB. In the SQL standard, this isolation level eliminates non-repeatable reads, but there are still phantom reads (multiple transactions modify the same record at the same time, and the transactions do not know each other exists. When the transaction is committed, the data modified by the subsequent transaction will be Overwrite the previous transaction, the previous transaction is like hallucination)

Serializable (Serializable): Completely serialized reading, each reading needs to obtain a table-level shared lock, and reading and writing will block each other.

The difference between non-repeatable reads and phantom reads is mainly: to solve non-repeatable reads, you need to lock the current record that meets the conditions, and to solve phantom reads, you need to lock the current records that meet the conditions and similar records. For example, if you query the information of a product, the repeatable read transaction isolation level can ensure that the current product information is locked to solve the non-repeatable read; but if you count the number of products and there is a record inserted in the middle, the repeatable read transaction isolation level cannot guarantee two The number of transaction statistics is the same.

19. Talk about the communication level of the transaction

Spring transactions define seven propagation mechanisms:

1. PROPAGATION_REQUIRED: The default Spring transaction propagation level, if there is a current transaction, join the transaction, if there is no transaction, create a new transaction.

2. PAOPAGATION_REQUIRE_NEW: If there is no current transaction, create a new transaction. If there is a current transaction, create a new transaction, and the old and new transactions are independent of each other. The rollback of an exception thrown by the external transaction will not affect the normal submission of the internal transaction.

3. PROPAGATION_NESTED: If there is a current transaction, it will be nested and executed in the current transaction. If there is no transaction currently, create a new transaction, similar to REQUIRE_NEW.

4. PROPAGATION_SUPPORTS: Support the current transaction, if there is no current transaction, it will be executed in a non-transactional manner.

5. PROPAGATION_NOT_SUPPORTED: Execute in a non-transactional manner, if there is a current transaction, suspend the current transaction.

6. PROPAGATION_MANDATORY: Mandatory transaction execution, if there is no current transaction, an exception will be thrown.

7. PROPAGATION_NEVER: Execute in a non-transactional manner, if there is a current transaction, an exception will be thrown.

The Spring transaction propagation level generally does not need to be defined, and the default is PROPAGATION_REQUIRED, unless it needs to be understood in the case of nested transactions.

20. Spring transaction implementation

Programmatic transaction management: This means that you can manage transactions programmatically, which brings a lot of flexibility, but is difficult to maintain.

Declarative transaction management: This approach means you can separate transaction management from business code. You just need to manage transactions through annotations or XML configuration.

21. What are the advantages of the transaction management of the Spring framework

It provides a unified programming model for different transaction APIs (such as JTA, JDBC, Hibernate, JPA, and JDO). It provides a simple API for programmatic transaction management rather than a series of complex transaction APIs (such as JTA). It supports declarative transaction management. It can be well integrated with Spring's various data access technologies.

It provides a unified programming model for different transaction APIs (such as JTA, JDBC, Hibernate, JPA, and JDO). It provides a simple API for programmatic transaction management rather than a series of complex transaction APIs (such as JTA). It supports declarative transaction management. It can be well integrated with Spring's various data access technologies.

It provides a unified programming model for different transaction APIs (such as JTA, JDBC, Hibernate, JPA, and JDO). It provides a simple API for programmatic transaction management rather than a series of complex transaction APIs (such as JTA). It supports declarative transaction management. It can be well integrated with Spring's various data access technologies.

22. What are the three elements of business?

Data source : Indicates a specific transactional resource, which is the real processor of the transaction, such as MySQL.

Transaction Manager : Like a big housekeeper, it manages the processing of transactions as a whole, such as opening, committing, rolling back, etc.

Transaction application and attribute configuration : like an identifier, indicating which methods to participate in transactions, how to participate in transactions, and some related attributes such as isolation level, timeout, etc.

23. What is the essence of transaction annotation?

@Transactional This annotation is just some (transaction-related) metadata, which is read and consumed by the transaction infrastructure at runtime, and uses these metadata to configure the bean's transaction behavior. Generally speaking, it has two functions. One is to indicate that the method should participate in the transaction, and the other is to configure related attributes to customize the participation method and operation behavior of the transaction.

Declarative transactions mainly benefit from Spring AOP. Use a transaction interceptor to perform transactional enhancements (advice) around/before and after method calls to drive transaction completion.

The @Transactional annotation can be marked on both the class and the method. When on a class, applies to all methods in the class by default. If the method is also marked at this time, the priority of the method is high. Also note that the method must be public.

Guess you like

Origin blog.csdn.net/weixin_43042683/article/details/131277022