3

For the upcoming gold nine silver ten, this article summarizes the classic Spring interview questions, a total of 2W words, it is recommended to collect and forward.

This series will systematically sort out the interview questions of MySQL, Redis, SSM framework, algorithm, computer network and other frequently asked technology stack interview questions. This article mainly organizes and shares Spring-related interview questions. MySQL has been updated before, and students who need it can also Check it out, I hope it will help those of you who are preparing for the fall!

Of course, all the interview questions organized by myself are shared free of charge. I just ask everyone to like, follow and forward for three consecutive times. These documents are placed at the end of the article, and students who need them can pick them up by themselves.

Spring overview

What is spring?

Spring is a lightweight Java development framework, first created by Rod Johnson to solve the coupling problem between the business logic layer and other layers of enterprise-level application development. It is a layered JavaSE/JavaEE full-stack (one-stop) lightweight open source framework that provides comprehensive infrastructure support for developing Java applications. Spring takes care of the infrastructure, so Java developers can focus on application development.

The most fundamental mission of Spring is to solve the complexity of enterprise application development, that is, to simplify Java development.

Spring can do a lot of things, it provides rich functions for enterprise-level development, but the bottom layer of these functions all rely on its two core features, namely dependency injection (DI) and aspect-oriented programming (aspect-oriented programming). oriented programming, AOP).

In order to reduce the complexity of Java development, Spring adopts the following 4 key strategies

  • Lightweight and minimally invasive programming based on POJOs;
  • Loose coupling through dependency injection and interface orientation;
  • Declarative programming based on aspects and conventions;
  • Reduce boilerplate code with aspects and templates.

What are the design goals, design concepts, and core of the Spring framework

Spring design goal: Spring provides developers with a one-stop lightweight application development platform;

Spring design concept: In JavaEE development, it supports POJO and JavaBean development methods, enables application-oriented development, and fully supports OO (object-oriented) design methods; Spring implements the management of object coupling relationships through the IoC container, and realizes dependency inversion. The dependencies between objects are handed over to the IoC container to achieve decoupling;

The core of the Spring framework: IoC container and AOP module. Manage POJO objects and their coupling relationships through the IoC container; enhance services in a dynamic and non-intrusive way through AOP.

IoC keeps cooperating components loosely coupled, while AOP programming allows you to separate out functionality across all layers of your application into reusable functional components.

What are the advantages and disadvantages of Spring?

advantage

  • Easy decoupling and simplified development
  • Spring is a big factory, which can hand over the creation of all objects and maintenance of dependencies to Spring management.
  • AOP programming support
  • Spring provides aspect-oriented programming, which can easily implement functions such as permission interception and operation monitoring of programs.
  • Declarative Transaction Support
  • Transaction management can be done only through configuration without manual programming.
  • Convenient program testing
  • Spring supports Junit4, and you can easily test Spring programs through annotations.
  • Easy to integrate various excellent frameworks
  • Spring does not exclude various excellent open source frameworks, and it provides direct support for various excellent frameworks (such as: Struts, Hibernate, MyBatis, etc.).
  • Reduce the difficulty of using JavaEE API
  • Spring provides encapsulation for some APIs (JDBC, JavaMail, remote calls, etc.) that are very difficult to use in JavaEE development, which greatly reduces the application difficulty of these APIs.

shortcoming

  • Spring is obviously a very lightweight framework, but it feels big and complete
  • Spring relies on reflection, which affects performance
  • The threshold for use is raised, and it takes a long time to get started with Spring

What are the application scenarios of Spring

Application scenario: JavaEE enterprise application development, including SSH, SSM, etc.

Spring value:

  • Spring is a non-intrusive framework, the goal is to minimize the application code's dependence on the framework;
  • Spring provides a consistent programming model that enables applications to be developed directly using POJOs, isolated from the runtime environment;
  • Spring promotes the change of application design style to object-oriented and interface-oriented development, which improves the reusability and testability of code;

What modules does Spring consist of?

Spring has about 20 modules in total, consisting of more than 1300 different files. And these components are respectively integrated in the core container (Core Container), AOP (Aspect Oriented Programming) and device support (Instrmentation), data access and integration (Data Access/Integeration), Web, message (Messaging), Test and other 6 modules middle. The following is the module structure diagram of Spring 5:

  • spring core: provides the basic components of the framework, including Inversion of Control (IOC) and Dependency Injection (DI) functions.
  • spring beans: BeanFactory is provided, which is a classic implementation of the factory pattern. Spring calls the management object Bean.
  • spring context: The context package built on the core package provides a framework-style object access method.
  • spring jdbc: Provides a JDBC abstraction layer, which eliminates cumbersome JDBC coding and database vendor-specific error code parsing, and is used to simplify JDBC.
  • spring aop: provides an aspect-oriented programming implementation, allowing you to customize interceptors, pointcuts, etc.
  • spring Web: Provides integrated features for Web development, such as file upload, ioc container initialization with servlet listeners, and ApplicationContext for Web.
  • spring test: It mainly provides support for testing, and supports unit testing and integration testing of Spring components using JUnit or TestNG.

What design patterns are used in the Spring framework?

  • Factory pattern: BeanFactory is the embodiment of the simple factory pattern, which is used to create instances of objects;
  • Singleton mode: Bean defaults to singleton mode.
  • Proxy mode: Spring's AOP function uses JDK's dynamic proxy and CGLIB bytecode generation technology;
  • Template method: used to solve the problem of code duplication. For example. RestTemplate, JmsTemplate, JpaTemplate.
  • Observer mode: Define a one-to-many dependency relationship between object keys. When the state of an object changes, all objects that depend on it will be notified to be braked and updated, such as the implementation of listener in Spring – ApplicationListener.

Explain the core container (spring context application context) module in detail

This is the basic Spring module that provides the basic functionality of the Spring Framework, and the BeanFactory is the core of any Spring-based application. The Spring Framework is built on top of this module, which makes Spring a container.

A bean factory is an implementation of the factory pattern that provides inversion of control to separate application configuration and dependencies from real application code. The most commonly used is
org.springframework.beans.factory.xml.XmlBeanFactory , which loads beans as defined in an XML file. The container reads configuration metadata from an XML file and uses it to create a fully configured system or application.

What are the different types of events in Spring framework

Spring provides the following five standard events:

Context update event (ContextRefreshedEvent): when calling
Triggered when the refresh method in the ConfigurableApplicationContext interface.

ContextStartedEvent: When the container calls
This event is fired when the Start method of the ConfigurableApplicationContext starts/restarts the container.

ContextStoppedEvent: When the container calls
This event is fired when the Stop method of the ConfigurableApplicationContext stops the container.

Context Closed Event (ContextClosedEvent): This event is fired when the ApplicationContext is closed. When the container is shut down, all singleton beans it manages are destroyed.

RequestHandledEvent: In a web application, this event is triggered when an http request (request) ends. If a bean implements the ApplicationListener interface, the bean is automatically notified when an ApplicationEvent is published.

What are the different components of a Spring application?

Spring applications generally have the following components:

  • Interface - defines functionality.
  • Bean class - It contains properties, setter and getter methods, functions, etc.
  • Bean Configuration File - Contains information about classes and how to configure them.
  • Spring Aspect Oriented Programming (AOP) - Provides the functionality of Aspect Oriented Programming.
  • User program - it uses the interface.

What are the ways to use Spring?

Use Spring in the following ways:

  • As a full-fledged Spring web application.
  • As a third-party web framework, use the Spring Frameworks middle tier.
  • As an Enterprise Java Bean, it can wrap existing POJOs (Plain Old Java Objects).
  • For remote use.

Spring Inversion of Control (IOC)

What is the Spring IOC container?

Inversion of Control is IoC (Inversion of Control), which transfers the calling rights of objects traditionally controlled directly by program code to the container, and the assembly and management of object components are realized through the container. The so-called "inversion of control" concept is the transfer of control of the component object from the program code itself to the external container.

Spring IOC is responsible for creating objects, managing objects (through dependency injection (DI), assembling objects, configuring objects, and managing the entire lifecycle of those objects.

What does Inversion of Control (IoC) do

  • Manages the creation of objects and the maintenance of dependencies. The creation of objects is not a simple matter. When the relationship between objects is complex, if the dependencies need to be maintained by programmers, it will be quite a headache.
  • Decoupling, the container maintains specific objects
  • The generation process of the class is managed. For example, we need to do some processing in the generation process of the class. The most direct example is the proxy. If there is a container program that can hand over this part of the processing to the container, the application does not need to care about how the class is completed. proxy

What are the advantages of IOC?

  • IOC or Dependency Injection minimizes the code size of the application.
  • It makes the application easy to test, unit testing no longer needs singleton and JNDI lookup mechanism.
  • Loose coupling is achieved with minimal effort and minimal intrusiveness.
  • The IOC container supports hungry initialization and lazy loading when loading services.

Implementation mechanism of Spring IoC

The implementation principle of IoC in Spring is the factory mode plus reflection mechanism.

Example:

interface Fruit {
public abstract void eat ;
} class Apple implements Fruit {
public void eat {
System.out.println("Apple");}} class Orange implements Fruit {
public void eat {
System.out.println("Orange");}} class Factory {
public static Fruit getInstance(String ClassName) {Fruit f=;try {f=(Fruit)Class.forName(ClassName).newInstance;} catch (Exception e) {e.printStackTrace;}return f;}} class Client {
public static void main (String[] a) {
Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");if(f!=){f.eat;}}}

What functions does Spring's IoC support

Spring's IoC design supports the following features:

  • dependency injection
  • dependency check
  • automatic assembly
  • support collection
  • Specify initialization and destruction methods
  • Support to call back some methods (but need to implement Spring interface, slightly intrusive)

Among them, the most important is dependency injection, which is the ref tag in terms of XML configuration. Corresponds to the Spring RuntimeBeanReference object.

For IoC, the most important thing is the container. The container manages the Bean's life cycle and controls the Bean's dependency injection.

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.

dependencies

BeanFactory: It is the bottom-level interface in Spring. It contains definitions of various beans, reads bean configuration documents, 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:

  • Inherits MessageSource, so internationalization is supported.
  • Unified resource file access method.
  • Provides events for registering beans in listeners.
  • 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.

Loading method

BeanFactroy uses lazy loading to inject beans, that is, only when a bean is used (getBean is called), the bean is loaded and instantiated. In this way, we can not find some existing Spring configuration problems. If a property of the Bean is not injected, after the BeanFacotry 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. By preloading all single-instance beans when the ApplicationContext starts, by pre-loading single-instance beans, you make sure that when you need them, you don't have to wait, because they've already been created.

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

how to create

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

way to register

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

How Spring designs containers, the relationship between BeanFactory and ApplicationContext is explained in detail

Spring author Rod Johnson designed two interfaces to represent containers.

  • BeanFactory
  • ApplicationContext

BeanFactory is simple and rude, it can be understood as a HashMap, Key is BeanName, Value is Bean instance. Usually only provide registration (put), access (get) these two functions. We can call it a "low-level container".

ApplicationContext can be called "advanced container". Because he has more functions than BeanFactory. He inherits multiple interfaces. So it has more functions. For example, resource acquisition, support for multiple messages (such as JSP tag support), and more tool-level support for BeanFactory. So you see his name, it is no longer a factory like BeanFactory, but an "application context", which represents all the functions of the entire large container. This interface defines a refresh method, which is most familiar to anyone reading Spring source code, for refreshing the entire container, ie reloading/refreshing all beans.

Of course, in addition to these two large interfaces, there are other auxiliary interfaces, and they will not be introduced here.

The relationship between BeanFactory and ApplicationContext

In order to show the relationship between "low-level container" and "high-level container" more intuitively, here we use the commonly used ClassPathXmlApplicationContext class to show the hierarchical UML relationship of the entire container.

a little complicated? Don't panic, let me explain.

The top one is BeanFactory, and the three green ones below are all function extension interfaces, so I won't go into details here.

Look at the pink "high-level container" belonging to the ApplicationContext below, which depends on the "low-level container". Here we are talking about dependencies, not inheritance. He relies on the "low-level container" getBean functionality. Advanced containers have more functions: support for different information sources, access to file resources, and support for application events (Observer mode).

Usually what the user sees is the "Advanced Container". But BeanFactory is also very useful!

The gray area on the left is the "low-level container", which only loads and loads beans and obtains beans. Other advanced features of containers are not available. For example, the refresh in the picture above refreshes all the configuration of the bean factory, the callback of life cycle events, etc.

summary

Having said so much, I wonder if you understand Spring IoC? Here is a summary: IoC can be implemented in Spring with only a low-level container, 2 steps:

  • Load the configuration file, parse it into BeanDefinition and put it in the Map.
  • When calling getBean, take out the Class object for instantiation from the Map to which the BeanDefinition belongs, and at the same time, if there is a dependency, the getBean method will be called recursively - to complete the dependency injection.

The above is the IoC of the Spring low-level container (BeanFactory).

As for the high-level container ApplicationContext, it contains the functions of the low-level container. When he executes the refresh template method, it will refresh the beans of the entire container. At the same time, as an advanced container, it contains too many functions. In a word, he is more than IoC. It supports different information sources, supports BeanFactory tool class, supports hierarchical containers, supports access to file resources, supports event publishing notifications, supports interface callbacks, and so on.

What is the usual implementation of ApplicationContext?

FileSystemXmlApplicationContext : This container loads bean definitions from an XML file. The full pathname of the XML Bean configuration file must be provided to its constructor.

ClassPathXmlApplicationContext: This container also loads the bean definitions from an XML file, here, you need to set the classpath correctly because the container will look for the bean configuration in the classpath.

WebXmlApplicationContext: This container loads an XML file that defines all the beans of a WEB application.

What is Spring's Dependency Injection?

Inversion of Control IoC is a big concept that can be implemented in different ways. There are two main ways to implement it: Dependency Injection and Dependency Lookup

Dependency Injection: Compared to IoC, Dependency Injection (DI) more accurately describes the design philosophy of IoC. The so-called Dependency Injection, that is, the dependencies between components are determined by the container during the runtime of the application system, that is, the container dynamically injects the target object instance of a certain dependency into each associated component in the application system. among. Components do not do positioning queries, but only provide ordinary Java methods for the container to determine dependencies.

Basic Principles of Dependency Injection

The basic principle of dependency injection is that application components should not be responsible for finding resources or other dependent collaborators. The work of configuring the object should be the responsibility of the IoC container, and the logic of "finding resources" should be extracted from the code of the application component and handed over to the IoC container. The container is solely responsible for the assembly of components, and it will pass the objects that meet the dependencies to the required objects through properties (setters in JavaBean) or constructors.

What are the advantages of dependency injection

Dependency injection is more popular because it is a more preferable way: let the container be solely responsible for the dependency lookup, and the managed component only needs to expose the JavaBean setter method or the constructor or interface with parameters, so that the container can be assembled at initialization time object dependencies. Compared with the dependency lookup method, its main advantages are:

  • Find and locate operations are completely independent of application code.
  • The container-independent API makes it easy to use application objects outside of any container.
  • No special interface is required, and most objects can be completely independent of the container.

What are the different types of dependency injection implementations?

Dependency injection is the most popular way of implementing IoC nowadays. Dependency injection is divided into three methods: Interface Injection, Setter Injection and Constructor Injection. Among them, interface injection has been abandoned since Spring 4 due to its poor flexibility and ease of use.

Constructor dependency injection: Constructor dependency injection is implemented by the container triggering the constructor of a class that has a series of parameters, each parameter representing a dependency on other classes.

Setter method injection: Setter method injection is that after the container instantiates the bean by calling the no-argument constructor or the no-argument static factory method, the setter method of the bean is called, that is, the setter-based dependency injection is implemented.

The difference between constructor dependency injection and setter method injection

Both dependency methods can be used, constructor injection and setter method injection. The best solution is to implement mandatory dependencies with constructor parameters and optional dependencies with setter methods.

Spring Beans

What are Spring beans?

Spring beans are those java objects that form the backbone of a Spring application. They are initialized, assembled, and managed by the Spring IOC container. These beans are created from metadata configured in the container. For example, it is defined in the form of an XML file.

What does a Spring Bean definition contain?

A Spring Bean definition contains all the configuration metadata that the container must know, including how to create a bean, its lifecycle details, and its dependencies.

How do I provide configuration metadata to the Spring container? Spring has several configuration methods

There are three important ways to provide configuration metadata to the Spring container.

  • XML configuration file.
  • Annotation-based configuration.
  • java based configuration.

What information does the Spring configuration file contain

A Spring configuration file is an XML file that contains class information, describes how to configure them, and how to call each other.

Several ways for Spring to inject beans based on xml

  • Set method injection;
  • Constructor injection: ① Set the position of the parameter by index; ② Set the parameter type by type;
  • static factory injection;
  • instance factory;

How do you define the scope of a class?

When defining a bean in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring wants to produce a new bean instance each time it is needed, the bean's scope property is specified as prototype. On the other hand, a bean must return the same instance every time it is used, and the bean's scope property must be set to singleton.

Explain the scope of several beans supported by Spring

The Spring Framework supports the following five bean scopes:

  • singleton : The bean has only one instance per Spring ioc container.
  • prototype: A bean definition can have multiple instances.
  • request: A bean is created for each http request. This scope is only valid in the context of a web-based Spring ApplicationContext.
  • 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.
  • global-session: In a global HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the context of a web-based Spring ApplicationContext.

Note: The default Spring bean scope is Singleton. The use of prototype scope requires careful thought, as frequent creation and destruction of beans can introduce significant performance overhead.

Are singleton beans in Spring framework thread safe?

No, singleton beans in Spring framework are not thread safe.

The beans in spring are singleton mode by default, and the spring framework does not encapsulate singleton beans for multi-threading.

In fact, most of the time spring beans are stateless (such as dao classes), and all beans are safe to some extent, but if the bean is stateful (such as view model objects), it is up to the developer to ensure thread safety. Now, the easiest thing is to change the scope of the bean and change "singleton" to "prototype", so that the request bean is equivalent to a new bean, so thread safety can be guaranteed.

  • Stateful means having data storage capabilities.
  • Stateless means no data is saved.

How does Spring handle thread concurrency issues?

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 adopts the method of "space for time".

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.

Explain the life cycle of beans in Spring framework

In traditional Java applications, the bean life cycle is simple. The bean is instantiated using the Java keyword new and the bean is ready to use. Once the bean is no longer in use, it is automatically garbage collected by Java. In contrast, the life cycle of beans in the Spring container is relatively complex. It is important to have a proper understanding of the Spring bean lifecycle because you may want to use the extension points provided by Spring to customize the bean creation process. The following figure shows a typical life cycle process of bean loading into the Spring application context.

A bean goes through several stages from creation to destruction in the Spring container, and each stage can be customized for how Spring manages the bean.

As you can see, the bean factory performs several startup steps before the bean is ready.

We describe the above figure in detail:

Spring instantiates beans;

Spring injects values and bean references into properties corresponding to the bean;

If the bean implements the BeanNameAware interface, Spring passes the bean's ID to the setBean-Name method;

If the bean implements the BeanFactoryAware interface, Spring will call the setBeanFactory method and pass in the BeanFactory container instance;

If the bean implements the ApplicationContextAware interface, Spring will call the setApplicationContext method and pass in the reference of the application context where the bean is located;

If beans implement the BeanPostProcessor interface, Spring will call their
post-ProcessBeforeInitialization method;

If beans implement the InitializingBean interface, Spring will call their after-PropertiesSet method. Similarly, if the bean declares an initialization method with initmethod, this method will also be called;

If beans implement the BeanPostProcessor interface, Spring will call their
post-ProcessAfterInitialization method;

At this point, the beans are ready to be used by the application, and they will stay in the application context until the application context is destroyed;

If the bean implements the DisposableBean interface, Spring will call its destroy interface method. Likewise, if the bean declares a destroy method with destroy-method, this method will also be called.

Now you have seen how to create and load a Spring container. But an empty container doesn't have much value, it has nothing in it until you put something in it. In order to benefit from Spring's DI (Dependency Injection), we must wire the application objects into the Spring container.

Which are the important bean lifecycle methods? Can you overload them?

There are two important bean lifecycle methods, the first is setup, which is called when the container loads the bean. The second method is teardown which is called when the container unloads the class.

The bean tag has two important attributes (init-method and destroy-method). With them you can customize initialization and logout methods yourself. They also have corresponding annotations (@PostConstruct and @PreDestroy).

What are Spring's internal beans? What are Spring inner beans?

In the Spring framework, when a bean is only used as a property of another bean, it can be declared as an inner bean. Internal beans can be implemented by injecting "properties" with setters and injecting "construction parameters" with constructors. Internal beans are usually anonymous, and their Scope is generally prototype.

How to inject a java collection in Spring?

Spring provides the following sets of configuration elements:

Type is used to inject a list of values, allowing the same value.

Types are used to inject a set of values, no identical values are allowed.

Type is used to inject a set of key-value pairs, both keys and values can be of any type.

Type is used to inject a set of key-value pairs, both keys and values can only be of type String.

What is bean assembly?

Assembly, or bean assembly, refers to assembling beans together in the Spring container, provided that the container needs to know the bean's dependencies and how to assemble them together through dependency injection.

What is autowiring of beans?

In the Spring framework, setting bean dependencies in the configuration file is a good mechanism. The Spring container can automatically assemble beans that cooperate with each other, which means that the container does not need to configure and can automatically handle the bean through the bean factory. collaboration. This means that Spring can automatically handle the dependencies between beans by injecting them into the Bean Factory. Autowiring can be set on each bean or on a specific bean.

Explain the different ways of autowiring, what are the ways for spring to autowire beans?

In spring, objects do not need to find or create other objects associated with them. The container is responsible for assigning object references that need to cooperate with each other to each object, and autowire is used to configure the automatic loading mode.

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

  • no: The default method is not to autowire the bean by manually setting the ref attribute.
  • byName: Autowire by the name of the bean. If the property of a bean is the same as the name of another bean, it will be autowired.
  • byType: Autowire by the data type of the parameter.
  • constructor: Use the constructor for assembly, and the parameters of the constructor are assembled through byType.
  • autodetect: Automatic detection, if there is a construction method, it will be automatically assembled by construct, otherwise it will be automatically assembled using byType.

What is the process of autowiring with @Autowired annotation?

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 starting spring IoC, the container is automatically loaded with a
AutowiredAnnotationBeanPostProcessor post-processor, when the container scans @Autowied, @Resource or @Inject, it will automatically find the required bean in the IoC container and assemble it to 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. As a workaround, use required=false.

What are the limitations of autowiring?

The limitations of autowiring are:

Override: You still need to define dependencies with and config, which means always override autowiring.

Primitive data types: You cannot autowire simple properties such as primitive data types, Strings, and classes.

Fuzzy feature: Autowiring is not as precise as explicit wiring, it is recommended to use explicit wiring if possible.

Can you inject one and an empty string in Spring? Can.

Spring annotations

What is Java-based Spring annotation configuration? Give some annotation examples

Java-based configuration allows you to do most of your Spring configuration with the help of a few Java annotations rather than through XML files.

Take the @Configuration annotation as an example, it is used to mark that a class can be used as a bean definition and used by the Spring IOC container.

Another example is the @Bean annotation, which indicates that this method will return an object that is registered as a bean into the Spring application context.

@Configuration
public class StudentConfig {
@Beanpublic StudentBean myStudent {return new StudentBean;}}

How to enable annotation assembly?

Annotation assembly is not enabled by default. In order to use annotation assembly, we must configure it in the Spring configuration file
context:annotation-config/ element.

What is the difference between @Component, @Controller, @Repository, @Service?

@Component: This marks the java class as a bean. It is a generic stereotype for any Spring-managed component. Spring's component scanning mechanism can now pick it up and pull it into the application environment.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it are automatically imported into the IoC container.

@Service: This annotation is a specialization of the component annotation. It does not provide any other behavior to the @Component annotation. You can use @Service instead of @Component in service layer classes as it specifies the intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar purpose and functionality. It provides additional benefits to DAOs. It imports the DAO into the IoC container and makes unchecked exceptions eligible for conversion to Spring DataAccessException.

What does the @Required annotation do?

This annotation indicates that the bean property must be set at configuration time, either via an explicit property value in a bean definition or via autowiring. If the @Required annotated bean property is not set, the container will throw
BeanInitializationException. Example:

public class Employee {
private String name;@Required public void setName (String name){
this.name=name;}public string getName{return name;}}

What does the @Autowired annotation do?

@Autowired is injected according to the type assembly by default. By default, it requires that the dependent object must exist (you can set its required property to false). The @Autowired annotation provides more fine-grained control, including where and how autowiring is done. It is used in the same way as @Required, to decorate setter methods, constructors, properties, or PN methods with arbitrary names and/or multiple parameters.

public class Employee {
private String name;@Autowired public void setName (String name) {
this.name=name;}public string getName{return name;}}

Difference between @Autowired and @Resource

@Autowired can be used for: constructors, member variables, setter methods

Difference between @Autowired and @Resource

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

@Resource assembles injection by name by default, and assembles injection by type only when no bean matching the name is found.

What does the @Qualifier annotation do?

When you create multiple beans of the same type and want to wire only one of them with properties, you can use the @Qualifier annotation and @Autowired to disambiguate by specifying which exact bean should be wired.

What is the use of the @RequestMapping annotation?

The @RequestMapping annotation is used to map a specific HTTP request method to a specific class/method in the controller that will handle the corresponding request. This annotation can be applied at two levels:

  • Class level: Map the requested URL
  • Method level: mapping URLs and HTTP request methods

Spring Data Access

Explain Object/Relational Mapping Integration Module

Spring supports us to use an object/relational mapping (ORM) tool on top of direct JDBC by providing ORM modules. Spring supports integration of mainstream ORM frameworks, such as Hiberate, JDO and iBATIS, JPA, TopLink, JDO, OJB. Spring's transaction management also supports all of the above ORM frameworks and JDBC.

How to use JDBC more efficiently in Spring framework?

With the Spring JDBC framework, the cost of resource management and error handling is mitigated. So developers only need to write statements and queries to access data from data, JDBC can also be used more effectively with the help of the template class provided by the Spring framework, this template is called JdbcTemplate

Explain the JDBC abstraction and the DAO module

By using JDBC abstraction and DAO module, the database code is kept concise, and the problems caused by the error closing of database resources can be avoided. It provides a unified exception access layer on top of the error information of various databases. It also utilizes Spring's AOP module to provide transaction management services for objects in Spring applications.

What is the use of spring DAO?

Spring DAO (Data Access Objects) makes it easier for data access technologies like JDBC, Hibernate or JDO to work in a unified way. This makes it easy for users to switch between persistence technologies. It also allows you to write code without thinking about catching exceptions that are different for each technology.

What classes exist in spring JDBC API?

  • JdbcTemplate
  • SimpleJdbcTemplate
  • NamedParameterJdbcTemplate
  • SimpleJdbcInsert
  • SimpleJdbcCall

What is JdbcTemplate

The JdbcTemplate class provides many convenient methods such as converting database data into basic data types or objects, executing written or callable database operation statements, and providing custom data error handling.

How can I access Hibernate using Spring? What are the ways to access Hibernate using Spring?

There are two ways to access Hibernate in Spring:

  • Inversion of Control with Hibernate Templates and Callbacks
  • Extend HibernateDAOSupport and apply AOP interceptor node

How to combine Spring and Hibernate via HibernateDaoSupport?

Call LocalSessionFactory with Spring's SessionFactory. The integration process is a three-step process:

  • Configure the Hibernate SessionFactory
  • Inherit HibernateDaoSupport to implement a DAO
  • Assembling in AOP-backed transactions

Types of transaction management supported by Spring, what are the implementation methods of spring transactions?

Spring supports two types of transaction management:

Programmatic transaction management: This means that you manage transactions programmatically, giving you great flexibility, but difficult to maintain.

Declarative transaction management: This means that you can separate business code and transaction management, you only need to use annotations and XML configuration to manage transactions.

The implementation and principle of Spring transaction

The essence of Spring transaction is actually the support of the database for transactions. Without the transaction support of the database, spring cannot provide transaction functions. The transaction commit and rollback of the real database layer is implemented through binlog or redo log.

Talk about Spring's transaction propagation behavior

The propagation behavior of spring transactions refers to how spring handles the behavior of these transactions when multiple transactions exist at the same time.

  • ① PROPAGATION_REQUIRED: If there is no current transaction, create a new transaction. If there is a current transaction, join the transaction. This setting is the most commonly used setting.
  • ② PROPAGATION_SUPPORTS: Support the current transaction. If there is a current transaction, join the transaction. If there is no current transaction, it will be executed as a non-transaction.
  • ③ PROPAGATION_MANDATORY: Support the current transaction, if there is a current transaction, join the transaction, if there is no current transaction, throw an exception.
  • ④ PROPAGATION_REQUIRES_NEW: Create a new transaction, regardless of whether there is a current transaction, create a new transaction.
  • ⑤ PROPAGATION_NOT_SUPPORTED: Execute the operation in a non-transactional manner. If there is a current transaction, suspend the current transaction.
  • ⑥ PROPAGATION_NEVER: Executed in a non-transactional manner, if there is a current transaction, an exception will be thrown.
  • ⑦ PROPAGATION_NESTED: If a transaction currently exists, it will be executed within a nested transaction. If there is no current transaction, it is executed according to the REQUIRED attribute.

Talk about spring's transaction isolation?

Spring has five isolation levels, the default value is ISOLATION_DEFAULT (using the database settings), and the other four isolation levels are consistent with the isolation level of the database:

ISOLATION_DEFAULT: Use the isolation level of the underlying database, and I will use whatever the database is set to;

ISOLATION_READ_UNCOMMITTED: Uncommitted read, the lowest isolation level, can be read by other transactions before the transaction is committed (there will be phantom reads, dirty reads, and non-repeatable reads);

ISOLATION_READ_COMMITTED: Commit read, a transaction can only be read by other transactions after it is committed (will cause phantom reads, non-repeatable reads), the default level of SQL server;

ISOLATION_REPEATABLE_READ: Repeatable read, to ensure that when reading the same data multiple times, its value is the same as the content at the beginning of the transaction, and it is forbidden to read uncommitted data of other transactions (which will cause phantom reads), the default level of MySQL ;

ISOLATION_SERIALIZABLE: Serialization, the most expensive and most reliable isolation level, this isolation level can prevent dirty reads, non-repeatable reads, and phantom reads.

Dirty read: Indicates that a transaction can read data that has not yet been committed in another transaction. For example, a transaction tries to insert record A, the transaction has not yet committed, and then another transaction tries to read record A.

Non-repeatable read: refers to reading the same data multiple times within a transaction.

Phantom read: Refers to different result sets returned by multiple queries within the same transaction. For example, the same transaction A has n records in the first query, but there are n+1 records in the second query under the same conditions, which seems to have an illusion. The reason for the phantom read is that another transaction adds or deletes or modifies the data in the result set of the first transaction. The data content of the same record is modified, and the records of all data rows increase or decrease.

What are the advantages of Spring Framework's transaction management?

  • Provides a constant programming model for different transaction APIs such as JTA, JDBC, Hibernate, JPA and JDO.
  • Provides a set of simple APIs for programmatic transaction management instead of some complex transaction APIs
  • Supports declarative transaction management.
  • It integrates well with Spring's various data access abstraction layers.

Which type of transaction management do you prefer?

Most users of the Spring Framework choose declarative transaction management because it has the least impact on application code and is therefore more in line with the idea of a non-intrusive, lightweight container. Declarative transaction management is better than programmatic transaction management, albeit with a little less flexibility than programmatic transaction management (which allows you to control transactions through code). The only disadvantage is that the most fine-grained can only be applied to the method level, and it cannot be applied to the code block level like programmatic transactions.

Spring Aspect Oriented Programming (AOP)

What is AOP

OOP (Object-Oriented Programming) object-oriented programming allows 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 each module.

AOP (Aspect-Oriented Programming), generally known as aspect-oriented programming, as a supplement to object-oriented, is used to extract and encapsulate public behaviors and logic that have nothing to do with business but affect multiple objects into a A reusable module, named "Aspect", reduces duplication of code in the system, reduces the coupling between modules, and improves the maintainability of the system. It can be used for authorization authentication, logging, transaction processing, etc.

What is the difference between Spring AOP and AspectJ AOP? What are the implementation methods of AOP?

The key to AOP implementation lies in the proxy mode. AOP proxies are mainly divided into static proxies and dynamic proxies. The representative of the static proxy is AspectJ; the dynamic proxy is 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 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.

The difference between JDK dynamic proxy and CGLIB dynamic proxy

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

JDK dynamic proxy only provides proxy for interface and does not support proxy for class. The core InvocationHandler interface and the Proxy class, the 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 to generate the target A proxy object for the 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.

The difference between static proxy and dynamic proxy is the timing of generating AOP proxy objects. Relatively speaking, AspectJ's static proxy method has better performance, but AspectJ requires a specific compiler to process, while Spring AOP does not require a specific compiler to process.

InvocationHandler's invoke(Object proxy,Method 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 parameter of a method of the proxy target instance, Used when method reflection is invoked.

How to understand proxies in Spring?

Objects created after applying advice to a target object are called proxies. In the case of client objects, the target object and the proxy object are the same.

Advice + Target Object = Proxy

Explain some nouns in Spring AOP

(1) Aspect: Aspect is a combination of advice and pointcut. Together, advice and pointcuts define what an aspect is all about. In Spring AOP, aspects can be implemented using generic classes (schema-based style) or in plain classes with @AspectJ annotation.

(2) Join point: refers to the method. In Spring AOP, a join point always represents the execution of a method. Apps may have thousands of occasional app notifications. These occasions are called join points. A join point is a point at which an aspect can be inserted during application execution. This point can be when a method is called, when an exception is thrown, or even when a field is modified. Aspect code can use these points to insert into the normal flow of the application and add new behavior.

(3) Advice: In AOP terminology, the work of an aspect is called an advice.

(4) Pointcut (Pointcut): The definition of the pointcut will match one or more join points to be woven into the advice. We usually specify these pointcuts using explicit class and method names, or using regular expression definitions to match class and method names.

(5) Introduction: Introduction allows us to add new methods or properties to an existing class.

(6) Target Object: An object that is advised by one or more aspects. It is usually a proxy object. Some people call it an advised object. Since Spring AOP is implemented through runtime proxies, this object is always a proxied object.

(7) Weaving: Weaving is the process of applying aspects to target objects and creating new proxy objects. How many points in the target object's life cycle can weaving:

Compile time: Aspects are woven in when the target class is compiled. AspectJ's weaving compiler weaves aspects in this way. Class loading time: Aspects are woven in when the target class is loaded into the JVM. A special class loader is required that enhances the bytecode of the target class before it is introduced into the application. AspectJ5's load-time weaving supports weaving aspects in this way. Runtime: Aspects are woven at some point during the application run. Typically, when weaving an aspect, the AOP container dynamically creates a proxy object for the target object. Spring AOP weaves aspects in this way.

Spring notifies objects at runtime

By wrapping aspects in proxy classes, Spring weaves aspects into Spring-managed beans at runtime. The proxy encapsulates the target class, intercepts the call to the notified method, and forwards the call to the real target bean. When the proxy intercepts a method call, the aspect logic is executed before calling the target bean method.

Spring does not create proxy objects until the application requires the bean to be proxied. If an ApplicationContext is used, Spring will only create the proxied object when the ApplicationContext loads all beans from the BeanFactory. Because the proxy object is only created at the Spring runtime, we don't need a special compiler to weave Spring AOP aspects.

Spring only supports method-level join points

Because Spring is based on dynamic proxies, Spring only supports method join points. Spring lacks support for field join points, and it doesn't support constructor join points. The connection point interception function outside the method, we can use Aspect to supplement.

In Spring AOP, what is the difference between concerns and crosscutting concerns? The difference between concern and cross-cutting concern in spring aop concerns (concern) is the behavior of a module in the application, a concern may be defined as a function we want to achieve.

A cross-cutting concern is a concern that is a feature that is used by the entire application and affects the entire application, such as logging, security, and data transfer, features that are required by almost every module of the application. So these are all cross-cutting concerns.

What are the types of Spring notifications?

In AOP terminology, the work of an aspect is called an advice and is actually a piece of code that is triggered by the Spring AOP framework when the program is executed.

Spring aspects can apply 5 types of advice:

  • Before notification (Before): call the notification function before the target method is called;
  • Post notification (After): Call notification after the target method is completed, and do not care what the output of the method is at this time;
  • Return notification (After-returning): call notification after the target method is successfully executed;
  • Exception notification (After-throwing): call notification after the target method throws an exception;
  • Around advice (Around): The advice wraps the advised method, performing custom actions before and after the advised method is called.

The same aspect, the execution order of different advice:

① Execution sequence without exception:

around before advice
before advicetarget method execute around after adviceafter adviceafterReturning

②Execution sequence in case of abnormal situation:

around before advice
before advicetarget method execute around after adviceafter adviceafterThrowing: exception occurred java.lang.RuntimeException: exception occurred

What is an Aspect?

Aspect consists of pointcount and advice, and aspect is a combination of advice and pointcut. It contains both the definition of cross-cutting logic and the definition of join points. Spring AOP is the framework responsible for implementing the aspect, and it weaves the cross-cutting logic defined by the aspect into the join point specified by the aspect. The focus of AOP's work It is how to enhance the connection point of the weaving target object, which includes two tasks:

  • How to locate a specific joinpoint through pointcut and advice
  • How to write aspect code in advice.

It can be simply considered that a class annotated with @Aspect is an aspect.

Explain the implementation of aspects based on XML Schema

In this case, aspects are implemented by regular classes as well as XML-based configuration.

Explain annotation-based aspect implementation

In this case (based on the @AspectJ implementation), the style of the aspect declaration involved is the same as that of a normal java class annotated with java5.

How many different types of automated agents are there?

  • BeanNameAutoProxyCreator
  • DefaultAdvisorAutoProxyCreator
  • Metadata autoproxying

Data collection

This article is written here first. I have sorted out some of the frequently asked questions in the interview, and will continue to update them later. Brothers who need PDF can like this article + follow [ click here ] to get it


Java架构师
179 声望69 粉丝