2023 Spring Eight-Part Essay - Interview Questions

Spring Overview(10)

1. What is spring?

Spring is a lightweight Java development framework that was 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-level application development, that is, to simplify Java development.

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

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

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

2. What is the design goal, design concept, 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, support POJO and JavaBean development methods, make application-oriented development, fully support OO (object-oriented) design method; Spring realizes object coupling relationship management through IoC container, and realizes dependency Inversion, hand over the dependencies between objects 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 collaborating components loosely coupled, while AOP programming allows you to separate the functions throughout the application layers to form reusable functional components.

3. What are the advantages and disadvantages of Spring?

**advantage**

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

**shortcoming**

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

4. 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 and isolated from the operating environment;
  • Spring promotes the transformation of application design style to object-oriented and interface-oriented development, improving code reusability and testability;

5. What modules does Spring consist of?

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

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-698FA9RN-1692509211712) (06-Spring Interview Questions (2020 latest version)-focus.assets/image-20201020183306246. png)]

  • spring core: Provides the basic components of the framework, including inversion of control (Inversion of Control, IOC) and dependency injection (Dependency Injection, DI) functions.
  • spring beans: BeanFactory is provided, which is a classic implementation of the factory pattern. Spring refers to management objects as beans.
  • spring context: The context package built on the basis of 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, point cuts, etc.
  • spring Web: Provides integrated features for Web development, such as file upload, ioc container initialization using 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.

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

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

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

This is the basic Spring module that provides the basic functions 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.

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

8. What are the different types of events in Spring framework

Spring provides the following five standard events:

  1. Context update event (ContextRefreshedEvent): It is triggered when the refresh() method in the ConfigurableApplicationContext interface is called.
  2. Context Start Event (ContextStartedEvent): This event is triggered when the container calls the Start() method of ConfigurableApplicationContext to start/restart the container.
  3. Context stop event (ContextStoppedEvent): This event is triggered when the container calls the Stop() method of ConfigurableApplicationContext to stop the container.
  4. Context closed event (ContextClosedEvent): This event is triggered when the ApplicationContext is closed. When a container is shut down, all singleton beans it manages are destroyed.
  5. Request Handled Event (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.

9. 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 functionality for aspect-oriented programming.
  • User Program − It uses the interface.

10. What are the ways to use Spring?

There are the following ways to use Spring:

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

Spring Inversion of Control (IOC) (13)

What is the Spring IOC container?

Inversion of Control is IoC (Inversion of Control), which converts objects that are traditionally directly manipulated by program code

The right to call the object is given to the container, and the assembly and management of the object components are realized through the container. The so-called "control

The concept of "transfer" is the transfer of control over the component object, from the program code itself to the external container.

Spring IOC is responsible for creating objects, managing objects (via dependency injection (DI), assembling objects, configuring objects, and managing the entire life cycle of these 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 object relationship is complex, if the dependency relationship needs to be maintained by the programmer, it is quite a headache.
  • Decoupling, the container maintains specific objects
  • It hosts the generation process of the class. 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 IOCs?

  • IOC or Dependency Injection keeps the code size of the application to a minimum.
  • It makes the application easy to test, unit testing does not require singletons and JNDI lookup mechanisms.
  • Loose coupling is possible with minimal overhead and minimal intrusion.
  • 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:

1 interface Fruit {
2 public abstract void eat();
3 }
4
5 class Apple implements Fruit {
6 public void eat(){
7 System.out.println("Apple");
8 }
9 }
10
11 class Orange implements Fruit {
12 public void eat(){
13 System.out.println("Orange");
14 }
15 }
16
17 class Factory {
18 public static Fruit getInstance(String ClassName) {
19 Fruit f=null;
20 try {
21 f=(Fruit)Class.forName(ClassName).newInstance();
22 } catch (Exception e) {
23 e.printStackTrace();
24 }
25 return f;
26 }
27 }
28
29 class Client {
30 public static void main(String[] a) {
31 Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");
32 if(f!=null){
33 f.eat();
34 }
35 }
36 }

What functions does Spring's IoC support

Spring's IoC design supports the following features: Dependency Injection Dependency Checking Autowiring Support for Collections Specifying Initializers and Destroyers

Support callback some methods (but need to implement Spring interface, slightly intrusive)

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

A RuntimeBeanReference object.

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

What is the difference between BeanFactory and ApplicationContext?

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

dependencies

BeanFactory: It is the lowest-level interface in Spring, which includes the 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.

The ApplicationContext interface is derived from BeanFactory, in addition to providing BeanFactory

In addition to some functions, it also provides more complete framework functions:

  • Inherit MessageSource, so it supports internationalization. Unified resource file access method.
  • Provides events to register beans in listeners.
  • Load multiple configuration files at the same time.
  • Load multiple (inherited) contexts, each dedicated to 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 (call getBean()), the bean is loaded and instantiated. In this way, we cannot find some existing Spring configuration problems. If a certain property of the Bean is not injected, after the BeanFacotry is loaded, an exception will not be thrown until the getBean method is called for the first time.

ApplicationContext, which creates all beans at once when the container starts. In this way, when the container starts, we can find the configuration errors in Spring, which is beneficial to check all

Whether the dependency property is injected. After the ApplicationContext is started, all single-instance beans are preloaded. By preloading single-instance beans, you can ensure that when you need them, you don't have to wait because they have already been created.

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

Creation method

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

way to register

Both BeanFactory and ApplicationContext support BeanPostProcessor,

BeanFactoryPostProcessor is used, but the difference between the two is: BeanFactory needs to be registered manually, while ApplicationContext is automatically registered.

How does Spring design containers, detailed explanation of the relationship between BeanFactory and ApplicationContext

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 a Bean instance. Usually only registration (put) and access (get) functions are provided. We can call it a "low-level container".

ApplicationContext can be called a "high-level container". Because he has more functions than BeanFactory. He inherits multiple interfaces. Therefore, it has more functions. For example, resource acquisition, support for various messages (such as JSP tag support), and more tool-level support for BeanFactory. So you can 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 the most familiar method for anyone who reads the Spring source code, and is used to refresh the entire container, that is, reload/refresh all beans.

Of course, in addition to these two major interfaces, there are other auxiliary interfaces, so I won’t introduce them 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.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-p5IbE3qY-1692509211712) (06-Spring Interview Questions (2020 latest version)-focus. Assets/container hierarchy .png)]

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 talk about it 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 dependency, not inheritance. He relies on the getBean function of the "low-level container"

able. The advanced container has more functions: it supports different information sources, can access file resources, and supports 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 the Bean and obtains the Bean. Other advanced features of containers are not available. For example, the refresh in the above picture refreshes all configurations of the Bean factory, lifecycle event callbacks, and so on.

summary

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

  1. Load the configuration file, parse it into BeanDefinition and put it in the Map.

  2. When calling getBean, from the Map to which the BeanDefinition belongs, take out

Class object is instantiated, and at the same time, if there is a dependency, the getBean method will be called recursively - completing 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 it 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 not just IoC. He supports different sources of information, supports

BeanFactory tool class, supports hierarchical containers, supports access to file resources, supports event release notifications, supports interface callbacks, and more.

What is the usual implementation of ApplicationContext?

FileSystemXmlApplicationContext: This container loads the definition of beans from an XML file, and the full path name of the XML Bean configuration file must be provided to its constructor.

ClassPathXmlApplicationContext: This container also loads beans definitions from an XML file, here, you need to set the classpath correctly because this container will look for bean configurations 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 and can be implemented in different ways. There are two main implementation methods: Dependency Injection and Dependency Lookup Dependency Injection: Compared with IoC, Dependency Injection (DI) more accurately describes the design concept of IoC. The so-called dependency injection (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 a target object instance of a certain dependency into each associated component in the application system among. Components do not perform location queries, but only provide common 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 collaborating objects. The work of configuring objects 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

The reason why dependency injection is more popular is that it is a more desirable way: let the container take full responsibility for dependency lookup, and managed components only need to expose JavaBean setter methods or parameterized constructors or receivers.

port that enables the container to assemble the object's dependencies at initialization time. Compared with the dependent lookup method, its main advantages are:

  • Lookup operations are completely independent of application code.
  • 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 IoC implementation nowadays. Dependency injection is divided into interface injection (Interface Injection), Setter method injection (Setter Injection) and constructor injection (Constructor Injection).

Injection) in three ways. 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 to call the setter method of the bean after the container instantiates the bean by calling the no-argument constructor or the no-argument static factory method, which realizes the setter-based dependency injection.

The difference between constructor dependency injection and setter method injection

constructor injection setter injection
no partial injection partially injected
Will not override setter properties will override the setter property
Any modification will create a new instance Any modification will not create a new instance
Good for setting many properties Good for setting a small number of properties

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

Spring Beans (19) 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, defined in the form of an XML file.

What does a Spring Bean definition contain?

A Spring Bean definition contains all the configuration metadata the container must know about the bean, its lifecycle details and its dependencies.

How to create a how to 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

The 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

  1. Set method injection;

  2. Constructor injection: ①Set the position of the parameter by index; ②Set the parameter type by type;

  3. static factory injection;

  4. 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 needs to generate a new bean instance each time, the scope attribute of the bean is specified as prototype. On the other hand, a bean must return the same instance each time it is used, and the scope attribute of the bean 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, and this scope is only valid in the case of a web-based SpringApplicationContext.
  • session: In an HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the case of a web-based Spring ApplicationContext.
  • global-session: In a global HTTP Session, a bean definition corresponds to a

instance. This scope is only valid in the case of a web-based Spring ApplicationContext.

Note: The default Spring bean scope is Singleton. The use of prototype scope requires careful thought, because frequent creation and destruction of beans will bring a large performance overhead.

Are singleton beans in Spring framework thread-safe?

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

The bean in spring defaults to the singleton mode, and the spring framework does not perform multi-threaded encapsulation processing on the singleton bean.

In fact, most of the time, spring beans are stateless (such as dao class), and all beans are also 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. The easiest way is to change the scope of the bean,

Change "singleton" to "prototype", so that the request bean is equivalent to new Bean(), so thread safety can be guaranteed.

  • To be stateful is to have a data storage function.
  • 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. Solve 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 "time-for-space" method, only one variable is provided, and different threads

The lock needs to be acquired, and threads that do not acquire the lock need to be queued. And ThreadLocal adopts the method of "space for time".

ThreadLocal will provide each thread with an independent copy of variables, thus isolating data access conflicts from multiple threads. Because each thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides a thread-safe shared object. When writing multi-threaded code, unsafe variables can be encapsulated into ThreadLocal. Explain the bean life cycle in the Spring framework

In traditional Java applications, the bean life cycle is very simple. The bean is instantiated using the Java keyword new, and the bean is then ready to use. Once the bean is no longer used, it is automatically garbage collected by Java. In contrast, the life cycle of beans in the Spring container is relatively more complicated. It is very important to correctly understand the life cycle of Spring beans, because you may need to use the extension points provided by Spring to customize the bean creation process. The figure below shows a typical life cycle process of bean loading into the Spring application context.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-gG50NCsq-1692509211713) (06-Spring Interview Questions (2020 latest version)-focus.assets/bean life cycle. png)]

Beans go through several stages from creation to destruction in the Spring container, and each stage can be customized for how Spring manages beans.

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 the bean;

Spring injects the value and bean reference into the corresponding property of the bean;

If the bean implements the BeanNameAware interface, Spring passes the bean's ID to the setBeanName() method;

If the bean implements the BeanFactoryAware interface, Spring will call the setBeanFactory() method

method, passing in the BeanFactory container instance;

If the bean implements the ApplicationContextAware interface, Spring will call the setApplicationContext() method to 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 the beans implement the InitializingBean interface, Spring will call their afterPropertiesSet() method. Similarly, if a bean declares an initialization method using initmethod,

This method will also be called;

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

ProcessAfterInitialization() method; at this point, beans are ready to be used by the application, and they will always reside in the application context until the application context is destroyed;

If the bean implements the DisposableBean interface, Spring will call its destroy() interface method

Law. Likewise, if the bean declares a destroy method using the destroy-method, that method will also be called.

You now know how to create and load a Spring container. But an empty container doesn't hold much value, it has nothing in it until you put something in it. order from Spring

To benefit from DI (Dependency Injection), we must assemble the application object into the Spring container.

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

There are two important bean life cycle methods, the first one is setup, which loads beans in the container

time is called. 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 the initialization and logout methods yourself. They also have corresponding annotations ( @PostConstruct and @PreDestroy ).

What are Spring's inner 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 configuration elements for collections: Types are used to inject a list of values, allowing identical values.

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

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

What is bean wiring?

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

What is bean autowiring?

In the Spring framework, it is a good mechanism to set the dependencies of beans in the configuration file.

The Spring container can automatically assemble beans that cooperate with each other, which means that the container does not need and configuration, and can pass

Collaboration between beans is automatically handled through a Bean factory. This means that Spring can pass to the Bean

The injection method in the Factory automatically handles the dependencies between beans. Autowiring can be set on a per-bean basis or on specific beans.

Explain the different ways of autowiring, what are the ways of spring autowiring 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 kinds of automatic assembly in the Spring framework xml configuration:

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

What is the process of autowiring with @Autowired annotation?

Use the @Autowired annotation to autowire specified beans. Before using the @Autowired annotation, it needs to be configured in the Spring configuration file.

When starting spring IoC, the container automatically loads 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 bean of the corresponding type in the container:

  • If the query result is exactly one, assemble the bean to the data specified by @Autowired;
  • If there is more than one query result, @Autowired will search 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: Overriding: You still need to define dependencies with and configure, which means autowiring always needs to be overridden.

Primitive Data Types: You cannot autowire simple properties such as primitive data types, String strings, and classes.

Fuzzy features: Autowiring is not as precise as explicit wiring, and explicit wiring is recommended if possible.

Can you inject a null and an empty string in Spring?

Can

Spring annotations (8)

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

Java-based configuration, allowing you to do most of your Spring configuration with the help of a few Java annotations instead of XML files.

Take the @Configuration annotation as an example, it is used to mark that a class can be regarded as a bean definition, and is

Used by the Spring IOC container.

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

1	@Configuration
2	public class StudentConfig {
3	@Bean
4	public StudentBean myStudent() {
5	return new StudentBean();
6	}
7	}

How to enable annotation assembly?

Annotation assembly is not enabled by default. In order to use annotation assembly, we must configure elements in the Spring configuration file.

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 component annotations. It does not provide any additional behavior to @Component annotations. You can use @Service instead of @Component in your 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 for DAOs. It imports DAOs into the IoC container and makes unchecked exceptions eligible to be converted to Spring DataAccessException.

What does the @Required annotation do

This annotation indicates that the properties of the bean must be set at configuration time, through an explicit property value defined by a bean or through automatic assembly. If the bean property of the @Required annotation is not set, the container will throw

BeanInitializationException. Example:

1	public class Employee {
2	private String name;
3	@Required
4	public void setName(String name){
5	this.name=name;
6	}
7	public string getName(){
8	return name;
9	}
10	}

What does the @Autowired annotation do

@Autowired is injected according to type assembly by default. By default, it requires that dependent objects must exist (you can set its required attribute to false). The @Autowired annotation provides finer-grained control over where and how autowiring is done. Its usage is the same as @Required to modify setter methods, constructors, properties or PN methods with arbitrary names and/or multiple parameters.

1	public class Employee {
2	private String name;
3	@Autowired
4	public void setName(String name) {
5	this.name=name;
6	}
7	public string getName(){
8	return name;
9	}
10	}

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 type assembly by default. By default, it requires that dependent objects must exist (you can set its required attribute to false).

@Resource is assembled and injected by name by default, and only when no bean matching the name is found will it be assembled and injected by type.

What does the @Qualifier annotation do

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

What is the use of @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: Mapping Requested URLs
  • Method level: mapping URLs and HTTP request methods

Spring Data Access (14)

Interpret Object/Relational Mapping Integration Module

By providing ORM modules, Spring supports us to use an object/relational mapping (ORM) tool on top of direct JDBC. Spring supports the 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 effectively in Spring Framework?

With the Spring JDBC framework, the overhead of resource management and error handling is mitigated. so the developer

Just write statements and queries to access data from the data, JDBC can also be used more efficiently with the help of template classes provided by the Spring framework, this template is called JdbcTemplate

Explain the JDBC abstraction and DAO module

By using JDBC abstraction and DAO module, the database code is kept concise and can avoid problems caused by incorrect closing of database resources. It provides a unified exception access layer on top of various database error messages. It also uses 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 data access objects such as JDBC, Hibernate or JDO

Asking technology is easier 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 having to worry 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 to use Spring to access Hibernate? What are the ways to access Hibernate using Spring?

There are two ways to access Hibernate in Spring:

  • Inversion of Control Using Hibernate Templates and Callbacks
  • ernateDAOSupport and apply the AOP interceptor node

How to combine Spring and Hibernate by extending Hib through HibernateDaoSupport?

Call LocalSessionFactory with Spring's SessionFactory. The integration process is divided into three steps:

  • Deploying the Hibernate SessionFactory
  • Inherit HibernateDaoSupport to implement a DAO
  • Assemble in an AOP supported transaction

What are the types of transaction management supported by Spring, and 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, which gives you great flexibility, but is difficult to maintain.

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

Implementation method and principle of Spring transaction

The essence of Spring transactions is actually the database's support for transactions. Without database transaction support,

Spring cannot provide transaction functions. The transaction commit and rollback of the real database layer are 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 transaction currently, join the transaction, if there is no transaction currently, execute it as a non-transaction.

③ PROPAGATION_MANDATORY: supports the current transaction, if there is a transaction currently, it will join the transaction, if there is no transaction currently, an exception will be thrown.

④ PROPAGATION_REQUIRES_NEW: Create a new transaction, regardless of whether there is currently a transaction, create a new transaction.

⑤ PROPAGATION_NOT_SUPPORTED: Perform operations in a non-transactional manner. If there is a current transaction, suspend the current transaction.

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

⑦ PROPAGATION_NESTED: If there is a current transaction, it will be executed in a nested transaction. If there is no transaction currently, execute according to the REQUIRED attribute.

Talk about spring transaction isolation?

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

\1. ISOLATION_DEFAULT: Use the underlying database to set the isolation level, and I will use whatever is set in the database;

\2. ISOLATION_READ_UNCOMMITTED: Uncommitted read, the lowest isolation level, before the transaction is committed, it can be read by other transactions (phantom reads, dirty reads, non-repeatable reads will occur); 3. ISOLATION_READ_COMMITTED: Committed read, after a transaction is committed can be read by other transactions (will cause phantom reads, non-repeatable reads), the default level of SQL server;

\4. ISOLATION_REPEATABLE_READ: Repeatable reading, to ensure that when the same data is read multiple times, its value is consistent with the content at the beginning of the transaction, and it is forbidden to read data that has not been submitted by other transactions (will cause phantom reading), MySQL the default level of

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

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

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

Phantom reading: refers to the fact that the result sets returned by multiple queries within the same transaction are different. 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 be an illusion. The reason for phantom reading is that another transaction adds or deletes or modifies the data in the result set of the first transaction. If the data content of the same record is modified, the records of all data rows will become more or less.

What are the advantages of transaction management in the Spring framework?

  • Provides an immutable 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 and supports declarative transaction management.
  • It is well integrated 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 the 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, although it is a little less flexible than programmatic transaction management (which allows you to control transactions through code). The only downside is that the finest granularity 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) (13) 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 various modules.

AOP (Aspect-Oriented Programming), commonly 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 one A reusable module, this module is named "Aspect", which reduces the duplication of code in the system, reduces the coupling between modules, and improves the maintainability of the system. Can be used for authority authentication, logging, transaction processing, etc.

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

The key to AOP implementation lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy. Static proxy is represented by AspectJ; 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, it is the enhanced AOP object when it is running.

(2) The dynamic proxy used by Spring AOP. The so-called dynamic proxy means that the AOP framework will not modify the bytecode, but will temporarily generate an AOP object for the method in memory every time it runs. This AOP

The object contains all the methods of the target object, and has been enhanced at a specific cut point, and the method of the original object is called back.

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 proxies only provide proxies for interfaces and do not support proxies for classes. The core InvocationHandler interface and Proxy class, InvocationHandler calls the code in the target class through the reflection of the invoke() method, and dynamically weaves the cross-cutting logic and business together; then, Proxy uses InvocationHandler to dynamically create an instance that conforms to a certain interface, Generate a proxy object of the target class.
  • If the proxy class does not implement the InvocationHandler interface, then Spring AOP will choose to use CGLIB to dynamically proxy the target class. CGLIB (Code Generation Library) is a class library for code generation, which can dynamically generate a subclass object of a specified class at runtime, and override specific methods and add enhanced codes to achieve 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 that the timing of generating AOP proxy objects is different. Relatively speaking, AspectJ's static proxy method has better performance, but AspectJ requires a specific compiler for processing, while

Spring AOP does not require specific compiler processing.

InvocationHandler 的 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, which is used when the method reflection is called.

How to understand proxies in Spring?

The 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 a few nouns in Spring AOP

(1) Aspect: Aspect is a combination of advice and pointcut. Advice and pointcuts together define the overall content of an aspect. In Spring AOP, aspects can be implemented using generic classes (pattern-based style) or in regular classes annotated with @AspectJ.

(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 opportunities are called join points. A join point is a point during application execution at which an aspect can be inserted. This point could 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 be inserted into the normal flow of the application and add new behavior.

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

(4) Pointcut: The definition of a pointcut matches one or more join points into which the advice is to be woven. We usually specify these pointcuts using explicit class and method names, or by using regular expressions to define the class and method names to match.

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

(6) Target Object: Notified by one or more aspects

(advise) object. It is usually a proxy object. It is also called being notified

(adviced) 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 life cycle of the target object can be weaved:

  • Compile time: Aspects are woven in when the target class is compiled. AspectJ's weaving compiler weaves aspects in this way.
  • Class loading period: The aspect is woven when the target class is loaded into the JVM. Special class loaders are required, which enhance the bytecode of a target class before it is brought into the application. AspectJ5's load-time weaving supports weaving aspects in this way.
  • Runtime: Aspects are woven in at some point during application execution. Generally, when weaving an aspect, the AOP container will dynamically create 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

middle. The proxy encapsulates the target class, intercepts the calls of the advised methods, and forwards the calls 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 the proxy object until the application needs the proxied bean. If you are using

For ApplicationContext, Spring will create proxied objects when ApplicationContext loads all beans from BeanFactory. Because the proxy object is created at 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's lack of fields can be supplemented by Aspect.

support for join points, and it does not support constructor join points. The connection point interception function outside the method, what is the difference between concern and cross-cutting concern in Spring AOP? The difference between concern and cross-cutting concern in spring aop

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 by the entire 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.

What are the types of Spring advice?

In AOP terminology, the work of an aspect is called advice, which is actually passed when the program is executed.

Code snippet triggered by the Spring AOP framework.

Spring aspects can apply 5 types of advice:

\1. Pre-notification (Before): call the notification function before the target method is called;

\2. Post-notification (After): Call the notification after the target method is completed, and do not care what the output of the method is at this time;

\3. Return notification (After-returning): call the notification after the target method is successfully executed;

\4. After-throwing: call the notification after the target method throws an exception;

\5. Around notification (Around): The notification wraps the notified method, and executes the custom behavior before and after the notified method is called.

The same aspect, the execution order of different advice:

① Execution sequence in case of no exception:

around before advice before advice target method 执行 around after advice after advice

afterReturning

② Execution sequence in case of exception: around before advice before advice target method execution around after advice after advice

afterThrowing: exception occurred java.lang.RuntimeException: exception occurred

What is an aspect aspect?

aspect is composed of pointcount and advice, and aspect is a combination of advice and pointcut. It includes both the definition of the cross-cutting logic and the definition of the connection point. Spring AOP is the framework responsible for implementing the aspect, which weaves the cross-cutting logic defined by the aspect into the connection point specified by the aspect.

The focus of AOP's work 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 classes annotated with @Aspect are aspects.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-LVHUYORZ-1692509211713) (06-Spring Interview Questions (2020 latest version)-focus.assets/Aspect Notes.png )]

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 implementation of @AspectJ), the style of the aspect declaration involved is consistent with the normal java class with java5 annotation.

How many different types of automated proxies are there?

BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

The same aspect, the execution order of different advice:

① Execution sequence in case of no exception:

around before advice before advice target method 执行 around after advice after advice

afterReturning

② Execution sequence in case of exception: around before advice before advice target method execution around after advice after advice

afterThrowing: exception occurred java.lang.RuntimeException: exception occurred

What is an aspect aspect?

aspect is composed of pointcount and advice, and aspect is a combination of advice and pointcut. It includes both the definition of the cross-cutting logic and the definition of the connection point. Spring AOP is the framework responsible for implementing the aspect, which weaves the cross-cutting logic defined by the aspect into the connection point specified by the aspect.

The focus of AOP's work 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 classes annotated with @Aspect are aspects.

[External link image transfer...(img-LVHUYORZ-1692509211713)]

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 implementation of @AspectJ), the style of the aspect declaration involved is consistent with the normal java class with java5 annotation.

How many different types of automated proxies are there?

BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

Metadata autoproxying

Guess you like

Origin blog.csdn.net/leader_song/article/details/132391123
Recommended