Spring interview questions (latest version of 2021)

Time:2021-6-11

Spring overview (10)

What is spring?

Spring isA lightweight java development frameworkThe earliestRod JohnsonThe purpose is to solve the coupling problem between business logic layer and other layers of enterprise application development. It is a layered javase / JavaEE full stack (one-stop) lightweight open source framework, which provides comprehensive infrastructure support for the development of Java applications. Spring is responsible for the infrastructure, so Java developers can focus on application development.

The fundamental mission of spring isTo 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 development, but the bottom of these functions depend on its two core features, namelyDependency injection (DI)*And*Aspect oriented programming (AOP)

In order to reduce the complexity of java development, spring adopts the following four key strategies

  • Lightweight and minimal invasive programming based on POJO;
  • Loose coupling is realized through dependency injection and interface oriented;
  • Declarative programming based on aspect and Convention;
  • Reduce boilerplate code through facets and templates.

What is the design goal, design concept and core of spring framework

Spring design goalsSpring provides a one-stop lightweight application development platform for developers;

Spring design conceptIn the development of Java EE, POJO and JavaBean are supported to make the application interface oriented and fully support OO (object-oriented) design method; Spring implements the management of object coupling relationship through IOC container, and realizes the dependency inversion, and gives the dependency relationship between objects to IOC container to realize decoupling;

The core of spring framework: IOC container and AOP module. POJO objects and their coupling relationship are managed by IOC container; Enhance services in a dynamic and non intrusive way through AOP.

IOC keeps loosely coupled components that cooperate with each other, while AOP programming allows you to separate the functions distributed in all layers of the application to form reusable functional components.

What are the advantages and disadvantages of spring?

advantage

  • Easy to decouple and simplify development

    Spring is a big factory, which can manage the creation of all objects and the maintenance of dependencies.

  • AOP programming support

    Spring provides aspect oriented programming, which can easily implement the functions of program permission interception and running monitoring.

  • Support for declarative transactions

    Only through configuration, transaction management can be completed without manual programming.

  • Convenient program testing

    Spring supports junit4 and can easily test spring programs through annotations.

  • Convenient integration of various excellent frameworks

    Spring does not exclude all kinds of excellent open source frameworks. It provides direct support for all kinds of excellent frameworks (such as struts, hibernate, mybatis, etc.).

  • Reduce the difficulty of using Java EE API

    Spring provides encapsulation for some very difficult APIs (JDBC, JavaMail, remote call, etc.) in Java EE development, which greatly reduces the application difficulty of these APIs.

shortcoming

  • Spring is a lightweight framework, but it feels big and complete
  • Spring relies on reflection, which affects performance
  • It takes a long time to get started with spring

What are the application scenarios of spring

Application scenariosJava EE enterprise application development, including SSH, SSM, etc

Spring value

  • Spring is a non intrusive framework, which aims to minimize the dependence of application code on the framework;
  • Spring provides a consistent programming model, which makes the application develop directly with POJO and separate from the running environment;
  • Spring promotes the transformation of application design style to object-oriented and interface oriented development, and improves the reusability and testability of code;

What modules does spring consist of?

Spring has about 20 modules in total, which are composed of more than 1300 different files. These components are integrated into theCore containerAOP (aspect oriented programming) and inspectionData access / integrationWebMessagingTestAnd so on. The following is the module structure of spring 5:

Spring interview questions (latest version of 2021)

  • 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 factory pattern. Spring calls the management object bean.
  • Spring context: Based on the core package, the context package provides a framework for object access.
  • Spring JDBC: provides an abstraction layer of JDBC, which eliminates the tedious JDBC coding and the error code analysis of database manufacturers, and is used to simplify JDBC.
  • Spring AOP: provides aspect oriented programming implementation, so that you can customize interceptors, tangent points, etc.
  • Spring Web: provides integrated features for web development, such as file upload, IOC container initialization using servlet listeners and application context for web.
  • Spring test: it mainly supports testing. It supports unit testing and integration testing of spring components using JUnit or TestNG.

What design patterns are used in spring framework?

  1. Factory mode: beanfactory is the embodiment of simple factory mode, which is used to create instances of objects;
  2. Singleton mode: bean is singleton mode by default.
  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, jmtemplate, and jpatemplate.
  5. Observer mode: defines a one to many dependency of an object key. When the state of an object changes, all the objects that depend on it will be notified to be 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, which provides the basic functions of spring framework. Beanfactory is the core of any application based on spring. The spring framework is built on top of this module, which makes spring a container.

Bean factory is an implementation of factory pattern, which provides control inversion function to separate application configuration and dependency from real application code. The most common is org. Springframework. Beans. Factory. XML. Xmlbeanfactory, which loads beans according to the definition in the XML file. The container reads the configuration metadata from the XML file and uses it to create a fully configured system or application.

What are the different types of events in the spring framework

Spring provides the following five standard events:

  1. Context refreshedevent: triggered when the refresh() method in the configurableapplicationcontext interface is called.
  2. Context started event: this event is triggered when the container calls the start() method of configurableapplicationcontext to start / restart the container.
  3. Context stopped event: this event is triggered when the container calls the stop() method of configurableapplicationcontext to stop the container.
  4. Context closed event: this event is triggered when ApplicationContext is closed. When the container is closed, all singleton beans managed by it are destroyed.
  5. Request handled event: in web applications, when an HTTP request ends, the event is triggered. If a bean implements the applicationlistener interface, the bean will be 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 the function.
  • Bean class – it contains properties, setters and getters, methods, functions, etc.
  • Bean configuration file – contains information about classes and how to configure them.
  • Spring aspect oriented programming (AOP) – provides aspect oriented programming capabilities.
  • User program – it uses the interface.

What are the ways to use spring?

You can use spring in the following ways:

  • As a mature spring web application.
  • As a third-party Web Framework, the spring frameworks middle layer is used.
  • As an enterprise java bean, it can wrap the existing POJO (plain old Java objects).
  • For remote use.

Spring control inversion (IOC) (13)

What is a spring IOC container?

Inversion of control is IOC (inversion of control). The so-called “control inversion” concept is the transfer of control over component objects from the program code itself to the external container.

Spring IOC is responsible for creating objects, managing objects (through DI), assembling objects, configuring objects, and managing the entire life cycle of these objects.

What is the role of inversion of control (IOC)

  • Management object creation and dependency maintenance. Object creation is not a simple thing. When the object relationship is complex, if the dependency needs to be maintained by the program, it is a headache
  • Decoupling, the container to maintain the specific object
  • Managed the generation process of a class. For example, we need to do some processing in the generation process of a class. The most direct example is the proxy. If a container program can give this part of processing to the container, the application program does not need to care about how the class completes the proxy

What are the advantages of IOC?

  • IOC or dependency injection minimizes the amount of application code.
  • It makes the application easy to test, unit test no longer need singleton and JNDI search mechanism.
  • The least cost and the least invasiveness make loose coupling possible.
  • IOC container supports starving initialization and lazy loading when loading services.

Implementation mechanism of spring IOC

The implementation principle of IOC in spring is 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=null;
        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!=null){
            f.eat();
        }
    }
}

What functions does spring’s IOC support

Spring’s IOC design supports the following functions:

  • Dependency injection
  • Dependency check
  • automatic assembly
  • Support collection
  • Specify the initialization and destruction methods
  • Support callback some methods (but need to implement spring interface, slightly intrusive)

Among them, the most important is dependency injection. From the configuration of XML, that is, ref tag. Corresponding to the spring 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 two core interfaces of spring, both of which can be used as containers of spring. ApplicationContext is the sub interface of beanfactory.

Dependency

Beanfactory: it is the lowest level interface in spring, including the definition of various beans, reading bean configuration documents, managing bean loading and instantiation, controlling bean life cycle, and maintaining bean dependencies.

As a derivative of beanfactory, ApplicationContext interface not only provides the functions of beanfactory, but also provides more complete framework functions

  • Inherits the message source and therefore supports internationalization.
  • Unified resource file access mode.
  • 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 level, such as the web layer of the application.

Loading mode

Beanfactroy injects a bean in the form of delayed loading, that is, only when a bean is used (call getBean ()), can the bean be loaded and instantiated. In this way, we can’t find some configuration problems of spring. If a bean attribute is not injected, after the beanfactory 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 helpful to check whether the dependent properties are injected. After the start of ApplicationContext, preload all single instance beans. By preloading single instance beans, you can ensure that you don’t have to wait when you need them, because they have been created.

Compared with the basic beanfactory, the only disadvantage of ApplicationContext is that it takes up memory space. When the application has more beans, the program starts slowly.

Creation method

Beanfactory is usually created programmatically, and ApplicationContext can also be created declaratively, such as using contextloader.

Registration method

Beanfactory and ApplicationContext both support the use of beanpostprocessor and beanfactory postprocessor, but the difference between them is that beanfactory needs to be registered manually, while ApplicationContext needs to be registered automatically.

How to design container in spring, the relationship between beanfactory and ApplicationContext

Spring author rod Johnson designed two interfaces to represent containers.

  • BeanFactory
  • ApplicationContext

Beanfactory is simple and crude. It can be understood as a HashMap. The key is the beanname and the value is the bean instance. Generally, it only provides the functions of put and get. We can call itLow level container

ApplicationContext can be calledAdvanced container. Because it has more functions than beanfactory. He inherited multiple interfaces. So it has more functions. For example, the acquisition of resources, support for a variety of messages (such as JSP tag support), beanfactory more tool level support. So you can see that his name is no longer a factory like beanfactory, but “application context”, which represents all the functions of the whole large container. The interface defines a refresh method, which is the most familiar method for anyone reading spring source code. It is used to refresh the whole container, that is, to reload / refresh all beans.

Of course, in addition to these two major interfaces, there are other auxiliary interfaces, which 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, we use the commonly used classpathxmlapplicationcontext class to show the hierarchical UML relationship of the whole container.

Spring interview questions (latest version of 2021)

A little complicated? Don’t panic. Let me explain.

The top one is beanfactory, and the bottom three green ones are all function extension interfaces. I won’t talk about them here.

Look at the following “high-level container” subordinate to ApplicationContext, which relies on “low-level container”. Here we are talking about dependency, not inheritance. He relies on the getBean function of the “low-level container.”. The advanced container has more functions: it supports different information sources, can access file resources, and supports application events (observer mode).

What users usually see is “advanced container”. But beanfactory is also enough!

In the gray area on the left is the “low level container”, which only loads the bean and obtains the bean. There are no other advanced functions of the container. For example, refresh in the picture above refreshes all configuration of bean factory, life cycle event callback, etc.

Summary

Having said so much, I wonder if you understand spring IOC? Here’s a summary: IOC can be implemented in spring with a low-level container. There are two steps:

  1. Load the configuration file, parse it into beandefinition and put it in the map.
  2. When calling getBean, the class object is instantiated from the map to which the beandefinition belongs. At the same time, if there are dependencies, the getBean method will be called recursively to complete dependency injection.

Above is the IOC of spring’s beanfactory.

As for the high-level container ApplicationContext, it contains the function of the low-level container. When it executes the refresh template method, it will refresh the bean of the whole container. At the same time, as an advanced container, it contains too many functions. In a word, it’s not just IOC. It supports different information sources, beanfactory tool classes, hierarchical containers, access to file resources, event release notification, interface callback and so on.

What is the usual implementation of ApplicationContext?

FileSystemXmlApplicationContext: this container loads the definition of beans 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 definition of beans from an XML file. Here, you need to set the classpath correctly, because the container will find 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?

Control inversion IOC is a big concept, which can be realized in different ways. There are two ways to implement it: dependency injection and dependency search

Dependency injection: compared with IOC, di describes the design concept of IOC more accurately. The so-called dependency injection means that the dependency relationship between components is determined by the container during the runtime of the application system, that is, the container dynamically injects the target object instance of a dependency relationship into each associated component in the application system. The component does not do location queries, but only provides 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 collaboration objects. The IOC container should be responsible for the work of configuring objects, and the logic of “finding resources” should be extracted from the code of application components and handed over to the IOC container. The container is fully responsible for the assembly of components. It will pass the objects that meet the dependency relationship to the required objects through attributes (setters in JavaBeans) or constructors.

What are the advantages of dependency injection

The reason why dependency injection is more popular is that it is a better way: let the container take full charge of dependency query, and the managed components only need to expose JavaBean setter methods or constructors or interfaces with parameters, so that the container can assemble the dependency relationship of objects during initialization. Compared with the dependent search method, the main advantages are as follows

  • The search and location operation has nothing to do with the application code.
  • Container independent API makes it easy to use application objects outside any container.
  • Without special interfaces, most objects can be completely independent of containers.

What are the different types of dependency injection implementations?

Dependency injection is the most popular way to implement IOC. Dependency injection includes interface injection, setter injection and constructor injection. Because of the poor flexibility and ease of use, interface injection has been abandoned since spring 4.

Constructor dependency injection: constructor dependency injection is realized by the container triggering the constructor of a class, which has a series of parameters, and each parameter represents a dependency on other classes.

Setter method injection: setter method injection means that after the container instantiates a bean by calling a parameterless constructor or a parameterless static factory method, it calls the setter method of the bean, that is, it realizes the setter based dependency injection.

Difference between constructor dependency injection and setter method injection

Spring interview questions (latest version of 2021)

Two dependency methods can be used: constructor injection and setter method injection. The best solution is to use constructor parameters to implement mandatory dependencies and setter methods to implement optional dependencies.

Spring Beans(19)

What is spring beans?

Spring beans are Java objects that form the backbone of spring applications. They are initialized, assembled, and managed by the spring IOC container. These beans are created through the metadata configured in the container. For example, in the form of an XML file.

What does a spring bean definition contain?

The definition of a spring bean contains all the configuration metadata that the container must know, including how to create a bean, its life cycle details and its dependencies.

How to provide configuration metadata for spring container? There are several ways to configure spring

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 and describes how to configure them and how to call each other.

Several ways of injecting beans into spring based on XML

  1. Set method injection;
  2. Constructor injection: ① setting the position of parameters through index; ② Parameter type is set by type;
  3. Static plant injection;
  4. Example 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 by the scope property in the bean definition. For example, when spring needs to produce a new bean instance each time, the scope property of the bean is specified as prototype. On the other hand, a bean must return the same instance every time it is used, and the scope property 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 :Bean has only one instance in each spring IOC container.
  • prototype: a bean definition can have multiple instances.
  • request: each HTTP request creates a bean, which is only valid in the case of Web-based spring ApplicationContext.
  • session: in an HTTP session, a bean definition corresponds to an instance. This scope is only valid in the case of 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 case of Web-based spring ApplicationContext.

be careful:The scope of the default spring bean is singleton. Using prototype scope requires careful thinking, because frequent bean creation and destruction will bring a lot of performance overhead.

Is singleton bean in spring framework thread safe?

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

Beans in spring are singleton mode by default, and spring framework does not encapsulate singleton beans by multithreading.

In fact, most of the time, spring beans are stateless (for example, Dao class). To some extent, beans are also safe. However, if beans are stateful (for example, view model object), developers need to ensure thread safety. The simplest way is to change the scope of beans and change “singleton” to “prototype”, In this way, the request bean is equivalent to new bean (), so thread safety can be guaranteed.

  • A state is a data storage function.
  • Stateless means that data will not be saved.

How does spring deal with thread concurrency?

In general, only stateless beans can be shared in a multithreaded environment. In spring, most beans can be declared as singleton scope, because spring uses ThreadLocal to deal with the non thread safe state of some beans to solve the thread safe problem.

Both ThreadLocal and thread synchronization mechanism are used to solve the access conflict of the same variable in multithreading. The synchronization mechanism adopts the method of “time for space”, which only provides one variable. Different threads need to obtain locks before accessing, and threads that do not obtain locks need to queue. ThreadLocal uses the method of “space for time”.

ThreadLocal will provide an independent variable copy for each thread, so as to isolate the data access conflicts of multiple threads. Because 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 multithreaded code, unsafe variables can be encapsulated into ThreadLocal.

Explain the bean life cycle in the spring framework

In traditional Java applications, bean life cycle is very simple. Use the Java keyword new to instantiate the bean, and then the bean can be used. Once the bean is no longer used, Java automatically garbage collection. In contrast, the bean life cycle in the spring container is much more complex. It’s very important to understand the life cycle of spring beans correctly, because you may need 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 spring application context.

Spring interview questions (latest version of 2021)

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

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

Let’s describe the above figure in detail

Spring instantiates beans;

Spring injects values and bean references into the bean’s corresponding properties;

If the bean implements the beannameaware interface, spring passes the bean ID to the setbean name() method;

If the bean implements the beanfactory aware 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 to pass in the reference of the application context in which the bean is located;

If the bean implements the beanpostprocessor interface, spring will call their post processbeforeinitialization () method;

If the bean implements the initializingbean interface, spring calls their after propertieset () method. Similarly, if a bean declares an initialization method using initmethod, the method will also be called;

If the bean implements the beanpostprocessor interface, spring will call their post processafterinitialization () method;

At this point, the beans are ready for use 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 calls its destroy () interface method. Similarly, if the bean declares a destroy method using the destroy method, the method is called.

Now you know how to create and load a spring container. But an empty container doesn’t have much value. There’s nothing in it before you put it in. In order to benefit from spring’s di (dependency injection), we have to assemble the application objects into the spring container.

What are the important bean lifecycle methods? Can you reload them?

There are two important bean life cycle methods. The first is setup, which is called when the bean is loaded by the container. The second method is teardown, which is called when the container unloads the class.

Bean tags have two important properties (init method and destroy method). With them, you can customize the initialization and logout methods. They also have corresponding annotations (@ postconstruct and @ predestroy).

What are spring’s internal beans? What is spring inner beans?

In the spring framework, when a bean is only used as an attribute of another bean, it can be declared as an internal bean. Internal beans can be implemented by injecting “properties” into setters and “construction parameters” into construction methods. Internal beans are usually anonymous, and their scope is generally prototype.

How to inject a Java collection into spring?

Spring provides configuration elements for the following sets:

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

Type is used to inject a set of values. The same value is not allowed.

Type is used to inject a set of key value pairs. Keys and values can be of any type.

Type is used to inject a set of key value pairs. The key and value can only be string type.

What is bean assembly?

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

What is automatic assembly of beans?

In the spring framework, it is a good mechanism to set bean dependencies in the configuration file. The spring container can automatically assemble beans that cooperate with each other, which means that the container does not need to be configured and can automatically handle the cooperation between beans through the bean factory. This means that spring can automatically handle the dependencies between beans by injecting them into bean factory. Automatic assembly can be set on each bean or on a specific bean.

Explain the different ways of automatic assembly. What are the ways of spring automatic assembly beans?

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

There are five kinds of automatic assembly in spring framework XML configuration

  • No: the default method is not to assemble beans automatically, but to assemble beans by manually setting the ref attribute.
  • Byname: automatically assemble by bean name. If the property of one bean is the same as the name of another bean, automatically assemble.
  • Bytype: automatic assembly by parameter data type.
  • 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 can be automatically assembled by the way of construct. Otherwise, it can be automatically assembled by the way of bytype.

What is the process of automatic assembly with @ Autowired annotation?

Use the @ Autowired annotation to automatically assemble the specified bean. Before using the @ Autowired annotation, you need to configure it in the spring configuration file< context:annotation-config / >。

When spring IOC is started, the container automatically loads an Autowired annotation beanpostprocessor postprocessor. When the container scans @ Autowired, @ resource or @ inject, it will automatically find the required bean in the IOC container and assemble the attribute 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 search is empty, an exception is thrown. To solve the problem, use required = false.

What are the limitations of automatic assembly?

The limitations of automatic assembly are as follows

rewrite: you still need to define dependencies with and configuration, which means that automatic assembly is always overridden.

Basic data type: you can’t automatically assemble simple properties such as basic data type, string, and class.

Fuzzy property: automatic assembly is not as accurate as explicit assembly. If possible, explicit assembly is recommended.

Can you inject a null and an empty string into spring?

sure.

Spring annotation (8)

What is java based spring annotation configuration? Give some examples of annotations

Java based configuration allows you to configure most of your spring with the help of a small amount of Java annotations, rather than through XML files.

Take the @ configuration annotation as an example. It is used to mark a class and can be used as a bean definition by the spring IOC container.

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

@Configuration
public class StudentConfig {
    @Bean
    public StudentBean myStudent() {
        return new StudentBean();
    }
}

How to open 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/>Elements.

@What’s the difference between component, @ controller, @ repository, @ service?

@Component: This marks the Java class as a bean. It is a generic stereotype of any spring management 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. The bean marked with it will be automatically imported into the IOC container.

@Service: this annotation is a specialization of Component annotation. It does not provide any other behavior for the @ Component annotation. You can use @ service instead of @ component in the service layer class because it specifies the intent in a better way.

@Repository: this annotation is a specialization of @ Component annotation with similar purposes and functions. It provides additional benefits for Dao. It imports the Dao into the IOC container and qualifies the unchecked exception to be converted to spring dataaccessexception.

@What is the use of the required annotation

This annotation indicates that the bean properties must be set during configuration, either through an explicit property value defined by a bean or through automatic assembly. If the bean properties of the @ required annotation are not set, the container will throw a beaninitializationexception. Example:

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

@What is the function of Autowired annotation

@Autowired is injected by type assembly by default. By default, it requires dependent objects to exist (you can set its required property to false)@ Autowired annotations provide more fine-grained control over where and how to complete automatic assembly. Like @ required, it modifies 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;
    }
}

@The difference between Autowired and @ resource

@Autowired can be used for: constructor, member variable, setter method

@The difference between Autowired and @ resource

  • @Autowired is injected by type assembly by default. By default, it requires dependent objects to exist (you can set its required property to false).
  • @Resource is assembled and injected by name by default. Only when no bean matching the name can it be assembled and injected by type.

@What is the use of qualifier annotations

When you create multiple beans of the same type and want to assemble only one of them with attributes, you can use @ qualifier annotation and @ Autowired to disambiguate by specifying which exact bean should be assembled.

@What’s 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 process the corresponding request. This annotation can be applied to two levels:

  • Class level: the URL of the mapping request
  • Method level: mapping URL and HTTP request method

Spring data access (14)

Interpretive object / relational mapping integration module

By providing ORM module, 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 hibernate, JDO and ibatis, JPA, TopLink, JDO and 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 spring JDBC framework, the cost of resource management and error handling will be reduced. Therefore, developers only need to write statements and queries to access data from data. JDBC can also be used more effectively with the help of template class provided by spring framework. This template is called jdbctemplate

Explain JDBC abstraction and Dao module

By using JDBC abstraction and Dao module, we can ensure the simplicity of database code, and avoid the problems caused by the wrong closing of database resources. It provides a unified exception access layer based on the error information of different databases. It also uses spring’s AOP module to provide transaction management services for objects in spring applications.

What’s the use of spring Dao?

Spring Dao (data access object) 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 a jdbctemplate

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

How can spring access Hibernate? What are the ways to use spring to access Hibernate?

There are two ways to access hibernate in spring:

  • Using hibernate template and callback to reverse control
  • Extending hibernatedaosupport and applying AOP interceptor node

How to combine spring and Hibernate through hibernatedaosupport?

Use spring’s sessionfactory to call localsessionfactory. The integration process is divided into three steps

  • Configure the hibernate sessionfactory
  • Implementing a Dao by inheriting hibernatedaosupport
  • Assemble in AOP supported transactions

What are the transaction management types supported by spring and how to implement spring transactions?

Spring supports two types of transaction management:

Programming managementThis means that you manage transactions programmatically, which gives you great flexibility, but it is difficult to maintain.

Declarative transaction managementThis means that you can separate business code from transaction management. You only need annotations and XML configuration to manage transactions.

The implementation method and principle of spring transaction

The essence of spring transaction is that the database supports transaction. Without the transaction support of database, spring cannot provide transaction function. The real transaction commit and rollback of database layer are realized by binlog or redo log.

Let’s talk about spring’s transaction propagation behavior

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

① PROPAGATION_ Required: if there is no current transaction, a new transaction will be created. If there is a current transaction, the transaction will be added. This is the most commonly used setting.

② PROPAGATION_ Supports: supports the current transaction. If there is a current transaction, it will join the transaction. If there is no current transaction, it will be executed as a non transaction.

③ PROPAGATION_ Mandatory: supports the current transaction. If there is a transaction, it will join the transaction. If there is no transaction, it will throw an exception.

④ PROPAGATION_ REQUIRES_ New: create a new transaction, no matter whether the current transaction exists or not.

⑤ PROPAGATION_ NOT_ Supported: the operation is performed in a non transactional manner. If there is a transaction, the current transaction will be suspended.

⑥ PROPAGATION_ Never: executed in a non transactional manner. If there is a transaction, an exception will be thrown.

⑦ PROPAGATION_ Nested: if a transaction currently exists, it is executed within a nested transaction. If there is no current transaction, the required property is used.

Let’s talk about the transaction isolation of spring?

Spring has five isolation levels, and the default value is isolation_ The other four isolation levels are consistent with the isolation level of the database

  1. ISOLATION_ Default: set the isolation level with the underlying database, and I will use whatever the database is set;
  2. ISOLATION_ READ_ Uncommitted: uncommitted read, the lowest isolation level, before the transaction is committed, it can be read by other transactions (phantom read, dirty read, non repeatable read will appear);
  3. ISOLATION_ READ_ Committed: committed to read. Only after a transaction is committed can it be read by other transactions (it will cause unreal read and non repeatable read). It is the default level of SQL server;
  4. ISOLATION_ REPEATABLE_ Read: it can be read repeatedly to ensure that when the same data is read many times, its value is consistent with the content at the beginning of the transaction. It is forbidden to read the uncommitted data of other transactions (which will cause unreal reading). It is the default level of MySQL;
  5. ISOLATION_ Serializable: serializable, the most expensive and reliable isolation level, which can prevent dirty read, non repeatable read and unreal read.

Dirty reading: indicates that one transaction can read uncommitted data in another transaction. For example, one transaction attempts to insert record a, which has not yet been committed, and then another transaction attempts to read record a.

Not repeatable: read the same data multiple times in a transaction.

Illusory reading: the result set returned by multiple queries in the same transaction is different. For example, there are n records in the first query of the same transaction a, but there are n + 1 records in the second query under the same conditions, which is like an illusion. The reason for unreal reading is that another transaction adds, deletes or modifies the data in the first transaction result set. If the data content of the same record is modified, the records of all data rows become more or less.

What are the advantages of transaction management in spring framework?

  • Provide a constant programming mode for different transaction APIs such as JTA, JDBC, hibernate, JPA and JDO.
  • It provides a set of simple API for programming transaction management instead of some complex transaction API
  • Support declarative transaction management.
  • And spring’s various data access abstraction layers are well integrated.

Which transaction management type do you prefer?

Most spring framework users choose declarative transaction management, because it has the least impact on application code, so it is more in line with the idea of a non intrusive lightweight container. Declarative transaction management is superior to programming transaction management, although it is less flexible than programming transaction management, which allows you to control transactions through code. The only drawback is that the most fine-grained can only be applied to the method level, and can not be applied to the code block level as the programming transaction.

Spring aspect oriented programming (AOP) (13)

What is AOP

OOP (object oriented programming) allows developers to define vertical relationships, but it is also suitable for defining horizontal relationships, which leads to a lot of code duplication and is not conducive to the reuse of each module.

AOP (aspect oriented programming), commonly known as aspect oriented programming, is a supplement to object-oriented programming. It is used to extract and encapsulate the common behaviors and logic that have nothing to do with business but have an impact on multiple objects into a reusable module, which is named “aspect” to reduce repetitive code in the system, It reduces the coupling degree between modules and improves the maintainability of the system. It can be used for authority authentication, log, transaction processing, etc.

What’s the difference between spring AOP and AspectJ AOP? What are the implementation methods of AOP?

The key of AOP implementation lies in agent mode, which is mainly divided into static agent and dynamic agent. The representative of static agent is AspectJ; Dynamic proxy is represented by spring AOP.

(1) AspectJ is an enhancement of static proxy. The so-called static proxy means that AOP framework will generate AOP proxy classes in the compilation phase, so it is also called compile time enhancement. It will weave AspectJ (aspect) into Java bytecode in the compilation phase, and the enhanced AOP object will be run.

(2) The dynamic proxy used by spring AOP, the so-called dynamic proxy, means that the AOP framework does not modify the bytecode, but temporarily generates an AOP object for the method in the memory every time it runs. This AOP object contains all the methods of the target object, and enhances them at a specific tangent point, and calls back the methods of the original object.

The difference between JDK dynamic proxy and cglib dynamic proxy

There are two main methods of dynamic proxy in spring AOP: JDK dynamic proxy and cglib dynamic proxy

  • JDK dynamic proxy only provides the proxy of interface, and does not support the proxy of class. The core invocationhandler interface and proxy class, invocationhandler calls the code in the target class through the reflection of the invoke () method, and weaves the crosscutting logic and business together dynamically; Then, the proxy uses the invocationhandler to dynamically create an instance that conforms to an interface and generate the proxy object of the target class.
  • If the proxy class does not implement the invocationhandler interface, spring AOP will choose to use cglib to dynamically proxy the target class. Cglib (Code Generation Library) is a class library of code generation, which can dynamically generate a subclass object of a specified class at runtime, and overlay specific methods and add enhanced code to achieve AOP. Cglib is a dynamic proxy through inheritance. Therefore, 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 needs a specific compiler to process, while spring AOP does not need a specific compiler to process.

Invoke (object proxy, method, object [] args) of invocationhandler: 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 is called by reflection.

How to understand the proxy in spring?

The object created after advice is applied to the target object is called a proxy. In the case of client objects, the target and proxy objects are the same.

Advice + Target Object = Proxy

Explain some terms in spring AOP

(1) Aspect: aspect is a combination of notification and pointcut. Notification and pointcut together define the whole content of the section. In spring AOP, facets can be implemented using generic classes (schema based style) or @ AspectJ annotations in generic classes.

(2) Join point: refers to a method. In spring AOP, a join point always represents the execution of a method. Applications may have thousands of opportunities to apply notifications. These moments are called join points. A join point is a point at which a section can be inserted during the execution of an application. This point can be when a method is called, when an exception is thrown, or even when a field is modified. The facet code can use these points to insert into the normal flow of the application and add new behaviors.

(3) Advice: in AOP terminology, the work of a section is called advice.

(4) Pointcut: the definition of the pointcut matches one or more join points to be woven into by the notification. We usually use explicit class and method names, or use regular expressions to define the matching class and method names to specify these pointcuts.

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

(6) Target object: an object that is advised by one or more aspects. It is usually a proxy object. Others call it an advised object. Since spring AOP is implemented through a runtime proxy, this object is always a proxied object.

(7) Weaving: weaving is the process of applying a section to a target object and creating a new proxy object. How many points can be woven into the life cycle of the target object

  • Compile time: facets are woven into the target class at compile time. AspectJ’s weaving compiler weaves the aspect in this way.
  • Class load period: facets are woven in when the target class is loaded into the JVM. A special class loader is needed to enhance the bytecode of the target class before it is introduced into the application. When aspectj5 is loaded, weaving in supports weaving in sections in this way.
  • Runtime: facets are woven in at some point in the application’s runtime. In general, the AOP container dynamically creates a proxy object for the target object when weaving in the section. This is how spring AOP weaves the cut.

Spring notifies objects at run time

By wrapping facets in proxy classes, spring weaves them into spring managed beans at runtime. The proxy encapsulates the target class, intercepts the call of the notified method, and forwards the call to the real target bean. When the proxy intercepts a method call, the facet logic is executed before calling the target bean method.

Spring does not create a proxy object until the application needs the bean to be proxy. If you are using ApplicationContext, spring will only create the proxy object when ApplicationContext loads all beans from beanfactory. Because the spring runtime only creates proxy objects, we don’t need a special compiler to weave the aspect of spring AOP.

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 does not support constructor join points. We can use aspect to supplement the join point interception function beyond method.

What is the difference between concerns and crosscutting concerns in spring AOP? Differences between concern and cross cutting concern in spring AOP

Concern is the behavior of a module in an application. A concern may be defined as a function that we want to implement.

Cross cutting concern is a concern. This concern is a function used by the whole application, and affects the whole application, such as logging, security and data transmission. Almost every module of the application needs the function. So these are crosscutting concerns.

What are the types of spring notifications?

In AOP terminology, aspect work is called notification, which is actually a code segment triggered by the spring AOP framework when a program is executed.

The spring aspect can apply five types of notifications:

  1. Pre notification (Before): calling the notification function before the target method is invoked.
  2. Post notification (After): calling notification after completion of the target method will not care what the output of the method is.
  3. Return notification (After-returning): call notification after successful execution of the target method;
  4. Exception notification (After-throwing): call notification after the target method throws an exception.
  5. Around notification: the notification wraps the notified method and performs custom behavior before and after the notified method call.
For the same aspect, the execution order of different advice is as follows:

① Execution sequence without exception:

around before advice
before advice
Target method execution
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 aspect?

Aspect is composed of pointcount and advice. Aspect is the combination of notification and pointcut. It includes not only the definition of crosscutting logic, but also the definition of join points. Spring AOP is the framework responsible for implementing the aspect, which weaves the crosscutting logic defined by the aspect into the join points specified by the aspect
AOP focuses on how to enhance the connection points of weaving target objects

  • How to locate a specific join point through pointcut and advice
  • How to write section code in advice

You can simply think of a class annotated with @ aspect as a facet

Spring interview questions (latest version of 2021)

Explain the implementation of section based on XML schema

In this case, facets are implemented by regular classes and XML based configurations.

Explain the annotation based facet implementation

In this case (based on the implementation of @ AspectJ), the style of aspect declaration involved is consistent with that of ordinary Java classes with java5 annotation.

How many different types of automatic agents are there?

BeanNameAutoProxyCreator

DefaultAdvisorAutoProxyCreator

Metadata autoproxying

Author: thinkwon
Source:https://www.bianchengquan.com…

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]