Preface:

Use Spring every day and have no idea how it works? How to use AOP and IOC and how do they work? And how exactly do you use notes? These are more concerned about the problem, today through a relatively long section to explain one by one, analysis of some basic usage and understanding.

In addition, I have compiled 20 years of interview questions, including Spring, concurrency, database, Redis, distributed, Dubbo, JVM, microservices and other aspects of the summary, the following is part of the screenshot, if necessaryClick here, click here”, code word nuggets.

I. Dependency Injection (Ioc)

1. What is the Spring IOC container?

At the heart of the Spring framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their full life cycle. The Spring container uses dependency injection to manage the components that make up an application. The container receives instructions for instantiating, configuring, and assembling objects by reading the provided configuration metadata. This metadata can be provided through XML, Java annotations, or Java code. 2. What is dependency injection?

In dependency injection, you don’t have to create objects, but you must describe how to create them. Rather than wiring components and services together directly in code, you describe which components in the configuration file require which services. The IoC container assembles them together.

3. How many ways can dependency injection be accomplished?

In general, dependency injection can be done in one of three ways:

Constructor injection Setter injection interface injection In the Spring Framework, only constructor and setter injection are used.

4. Distinguish constructor injection from setter injection. 5. How many IOC containers are available in Spring?

BeanFactory – BeanFactory is like a factory class that contains a collection of beans. It instantiates the bean when requested by the client.

ApplicationContext – The ApplicationContext interface extends the BeanFactory interface. It provides some additional functionality on top of the BeanFactory.

6. Distinguish between BeanFactory and ApplicationContext. 7. List some benefits of IoC.

Some of the benefits of IoC are:

It minimizes the amount of code in your application. It will make your application easy to test because it does not require any singletons or JNDI lookups in a unit test case. It promotes loose coupling with minimal impact and minimal intrusion mechanisms. It supports instant instantiation and lazy loading of services.

8. 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(a);
}
class Apple implements Fruit {
    public void eat(a){
        System.out.println("Apple"); }}class Orange implements Fruit {
    public void eat(a){
        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();
        }
        returnf; }}class Client {
    public static void main(String[] a) {
        Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");
        if(f! =null){ f.eat(); }}}Copy the code

Second, the AOP

1. What is AOP?

AOP(aspect-oriented Programming), namely Aspect Oriented Programming, is complementary to OOP(Object-oriented Programming) and provides a different perspective of abstract software structure from OOP. In OOP, we use classes as our base unit, whereas in AOP, the base unit is aspects

2. What are the aspects, Advice, Pointcut, JointPoint, and Advice parameters in AOP?

  • Aspect-aspect is a class that implements intersecting problems, such as transaction management. The Aspect can be a plain class configured and then configured in the Spring Bean configuration file, or we can declare the class as an Aspect using the @Aspect annotation supported by Spring AspectJ.
  • Advice – Advice is the action taken for a specific JoinPoint. Programmatically, they are methods that are executed when a specific JoinPoint with a matching pointcut is reached in an application. You can think of Advice as a Spring Interceptor or a Servlet filter.
  • Advice Arguments – We can pass Arguments in Advice methods. We can use the args() expression in the pointcut to apply to any method that matches the parameter pattern. If we use it, then we need to use the same name in the advice method that determines the parameter type.
  • Pointcut – Pointcut is a regular expression that matches JoinPoint and is used to determine whether Advice needs to be performed. Pointcut uses a different type of expression that matches JoinPoint. The Spring framework uses the AspectJ Pointcut expression language to determine the JoinPoint to which the notification method will be applied.
  • JoinPoint – JoinPoint is a specific point in an application, such as method execution, exception handling, changing object variable values, etc. In Spring AOP, JoinPoint is always the executor of a method.

3. What is Advice?

The action taken by the Aspect at a particular JoinPoint is called Advice. Spring AOP maintains a series of interceptors “around” JoinPoint using an Advice as an interceptor.

4. What kind of Advice is there?

Before – These types of Advice are executed Before the JoinPoint method and configured using the @before annotation tag. AfterReturning – These types of Advice are executed After normal execution of join point methods and are configured using the @AfterRETURNING annotation flag. AfterThrowing – These types of Advice are only performed when the JoinPoint method exits by Throwing an exception and is configured using the @AfterThrowing annotation tag. After (finally) – These types of Advice are executed After the join point method, whether the method exit returns normally or abnormally, and are configured using the @After annotation flag. Around – These types of Advice are executed before and after join points and are configured using the @around annotation tag. 5. In Spring AOP, concern and cross-cutting concern are different.

Concern is the behavior we want to define in a particular module of our application. It can be defined as the functionality we want to implement.

Cross-cutting Concern is an application-wide behavior that affects the entire application. For example, logging, security, and data transfer are issues that need to be addressed by almost every module of the application, so they are cross-domain issues.

6. What are the implementations of AOP?

The technologies for implementing AOP fall into two main categories:

Static proxy – refers to compilation using commands provided by the AOP framework so that AOP proxy classes can be generated at compile time, hence also called compile-time enhancement; Compile-time weaving (special compiler implementation) class-time weaving (special classloader implementation). Dynamic proxy – Generates AOP dynamic proxy classes “temporarily” in memory at run time and is therefore also known as runtime enhancement. Spring AOP and AspectJ AOP

Spring AOP is implemented based on dynamic proxy; AspectJ is implemented using static proxies. Spring AOP supports only method-level pointcuts; Full AOP support is provided, and it also supports property-level pointcuts.

8. How to understand proxies in Spring?

The objects created after Advice is applied to the target object are called proxies. In the case of the client object, the target object and the proxy object are identical.

1 Advice + Target Object = Proxy

9. What does Weaving mean?

Weaving links an aspect to other application types or objects in order to create an advice object. In Spring AOP, weaving is performed at run time. Please refer to the picture below:

Third, Beans

1. What is Spring bean?

They are the objects that form the backbone of a user’s application. Beans are managed by the Spring IoC container. They are instantiated, configured, assembled, and managed by the Spring IoC container. Beans are created based on configuration metadata provided by the user to the container. 2. What configuration methods does Spring provide?

Xml-based Configuration

The dependencies and services required by the bean are specified in an XML-formatted configuration file. These configuration files typically contain many bean definitions and application-specific configuration options. They usually start with a bean label. Such as:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
        <property name="name" value="Edureka"></property>
    </bean>
Copy the code

Annotation-based configuration

Instead of using XML to describe bean assembly, you can configure beans as component classes themselves by using annotations on the associated class, method, or field declarations. By default, the annotation assembly is not open in the Spring container. Therefore, you need to enable it in your Spring configuration file before using it. Such as:

<beans> <context:annotation-config/> <! -- bean definitions go here --> </beans>Copy the code

Java API-based configuration

Spring’s Java Configuration is implemented using @Beans and @Configuration.

2.1.@Bean Annotations play the same role as elements.

The @Configuration class allows you to define inter-bean dependencies by simply calling other @Bean methods in the same class.

Such as:

public class StudentConfig {
    @Bean
    public StudentBean myStudent(a) {
        return newStudentBean(); }}Copy the code

3. Spring supports centralized bean scopes?

Spring beans support five scopes:

Singleton – Only one single instance per Spring IoC container. Prototype – Each request generates a new instance. Request – Each HTTP Request generates a new instance, and the bean is only valid within the current HTTP Request. Session – Each HTTP request generates a new bean that is valid only for the current HTTP Session. Global-session – is similar to the standard HTTP session scope, but only makes sense in portlet-based Web applications. The Portlet specification defines the concept of a global Session, which is shared by all the different portlets that make up a Portlet Web application. Beans defined in the Global Session scope are limited to the lifecycle of the global Portlet session. If you use the Global Session scope on the Web to identify beans, the Web will automatically use it as a session type. The last three are available only if the user uses a Web-enabled ApplicationContext.

4. What is the lifecycle of the Spring Bean container?

The lifecycle flow of the Spring Bean container is as follows:

4.1. The Spring container instantiates beans from the bean definition in the configuration.

4.2. Spring uses dependency injection to populate all properties, as defined in the bean configuration.

4.3. If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing the bean ID.

4.4. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself.

4.5. If there is any BeanPostProcessors associated with bean, call the preProcessBeforeInitialization () method.

4.6. If the init method (of the init-method property) is specified for the bean, it will be called.

4.7. In the end, if there is any BeanPostProcessors associated with bean, will call postProcessAfterInitialization () method.

4.8. If the bean implements the DisposableBean interface, destory() will be called when the Spring container closes.

4.9. If the destroy method (with the destroy-method attribute) is specified for the bean, it will be called. 5. What are Spring’s internal beans?

A bean can only be declared as an internal bean if it is used as a property of another bean. To define beans, Spring’s XML-based configuration metadata provides the use of elements in or. Inner beans are always anonymous; they are always prototypes.

For example, suppose we have a Student class that references the Person class. Here we will just create an instance of the Person class and use it in Student.

Student.java

public class Student {
    private Person person;
    //Setters and Getters
}
public class Person {
    private String name;
    private String address;
    //Setters and Getters
}
Copy the code

bean.xml

The < bean id = "StudentBean" class="com.edureka.Student"> person"> <! --This is inner bean --> <bean class="com.edureka.Person"> name"Value =" Scott"></property>
                <property name="address"Value = "Bangalore">   Copy the code

6. What is Spring assembly

When beans are combined together in the Spring container, it is called assembly or bean assembly. The Spring container needs to know what beans are required and how the container should use dependency injection to bind the beans together and assemble them.

7. What are the methods of automatic assembly?

The Spring container can automatically assemble beans. That is, Spring can automatically resolve the bean’s collaborators by examining the contents of the BeanFactory.

Different modes of automatic assembly:

No – This is the default setting, indicating no autowiring. Assembly should be done using explicit bean references.

ByName – It injects object dependencies based on the bean name. It matches and assembles its attributes with beans defined by the same name in the XML file.

ByType – It injects object dependencies based on type. If the type of the attribute matches a bean name in the XML file, the attribute is matched and assembled.

Constructor – It injects dependencies by calling the constructor of the class. It has a lot of parameters.

Autodetect – First the container tries to assemble using Autowire via constructors, and if not, tries byType autoassembly.

8. What are the limitations of autowiring?

Possibility of override – You can always use and set specified dependencies that will override autowiring.

Basic metadata types – Simple properties (such as primitive data types, strings, and classes) cannot be assembled automatically.

Confusing nature – always prefer to use explicit assembly because autoassembly is not very accurate.

Four, annotations,

1. What important Spring annotations have you used?

  • Controller – The Controller class used in the Spring MVC project.
  • @service – For Service classes.
  • @requestMapping – Used to configure URI mapping in controller handler methods.
  • ResponseBody – Used to send an Object as a response, usually to send XML or JSON data as a response.
  • @pathVariable – Used to map dynamic values from URIs to handler method parameters.
  • Autowired – Used to automatically assemble dependencies in Spring beans.
  • @Qualifier – Use the @AutoWired annotation to avoid confusion when there are multiple instances of the bean type.
  • @scope – Used to configure the Scope of the Spring bean.
  • @Configuration, @ComponentScan, and @Bean – for Java-based Configuration.
  • @aspect, @before, @after, @around, @pointcut – for Aspect programming (AOP).

2. How do I start annotation assembly in Spring?

By default, the annotation assembly is not open in the Spring container. Therefore, to use annotation-based assembly, we must enable it in the Spring configuration file by configuring the <context: annotation-config /> element.

3. What is the difference between @Component, @Controller, @repository and @service?

@Component: This marks the Java class as a bean. It is a common stereotype for any Spring management component. Spring’s component scanning mechanism can now pick them up and pull them into the application environment.

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

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

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

4. What is the use of the @required annotation?

@required applies to the bean property setter method. This annotation merely indicates that the explicit property values in the bean definition must be used at configuration time or the affected bean properties must be populated with autoassembly. If it is not already filled the bean properties affected, the container will throw BeanInitializationException.

Example:

public class Employee {
    private String name;
    @Required
    public void setName(String name){
        this.name=name;
    }
    public string getName(a){
        returnname; }}Copy the code

5. What is the use of @autowired annotations?

@autoWired gives you more control over where and how autoassembly should take place. This annotation is used to automatically assemble beans on setter methods, constructors, properties or methods with arbitrary names or multiple parameters. By default, it is type-driven injection.

public class Employee {
    private String name;
    @Autowired
    public void setName(String name) {
        this.name=name;
    }
    public string getName(a){
        returnname; }}Copy the code

6. What is the use of @Qualifier annotations?

When you create multiple beans of the same type and want to assemble only one of them using properties, you can use the @Qualifier annotation and @AutoWired to disambiguously specify which exact bean should be assembled.

For example, here we have two classes, Employee and EmpAccount. In EmpAccount, the @Qualifier is used to specify that a bean with ID EMP1 must be assembled.

Employee.java

public class Employee {
    private String name;
    @Autowired
    public void setName(String name) {
        this.name=name;
    }
    public string getName(a) {
        returnname; }}Copy the code

EmpAccount.java

public class EmpAccount {
    private Employee emp;

    @Autowired
    @Qualifier(emp1)
    public void showName(a) {system.out. println(" Employee name: "+emp.getName); }}Copy the code

7. What does @requestMapping do?

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: URL of the mapping request

Method level: mapping URLS and HTTP request methods

5. Data access

1. What is the use of spring DAO?

The Spring DAO 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 having to worry about catching exceptions that are different for each technology.

2. List exceptions thrown by the Spring DAO.

3. What classes exist in the Spring JDBC API?

JdbcTemplate

SimpleJdbcTemplate

NamedParameterJdbcTemplate

SimpleJdbcInsert

SimpleJdbcCall

4. What are the ways to access Hibernate using Spring?

We can use Spring to access Hibernate in two ways:

4.1. Inversion of control using Hibernate templates and callbacks

4.2. Extend Hibernateda Support and apply the AOP interceptor node

5. List the transaction management types supported by Spring

Spring supports two types of transaction management:

5.1. Programmatic transaction Management: In this process, transactions are managed with the help of programming. It gives you great flexibility, but is very difficult to maintain.

5.2. Declarative transaction Management: Here, transaction management is separated from the business code. Use only annotations or XML-based configurations to manage transactions.

6. Which ORM frameworks spring supports

Hibernate

iBatis

JPA

JDO

OJB

Sixth, the MVC

1. What is the use of the Spring MVC framework?

The Spring Web MVC framework provides a model-View-controller architecture and ready-to-use components for developing flexible and loosely coupled Web applications. The MVC pattern helps separate different aspects of an application, such as input logic, business logic, and UI logic, while providing loose coupling between all these elements.

2. Describe the workflow of DispatcherServlet

The workflow of the DispatcherServlet can be illustrated with a diagram:

2.1. Send an HTTP request to the server, which is captured by the front-end controller DispatcherServlet.

2.2. DispatcherServlet parses the requested URL according to the configuration in -servlet.xml and obtains the requested resource identifier (URI). Then, based on the URI, HandlerMapping is called to retrieve all relevant objects (including Handler objects and interceptors corresponding to Handler objects) configured by this Handler, which are returned as HandlerExecutionChain objects.

2.3. The DispatcherServlet selects a suitable HandlerAdapter according to the Handler obtained. (Note: If the HandlerAdapter is successfully obtained, execution of the interceptor’s preHandler(…) begins at this point.) Methods).

2.4. Extract the model data from the Request, populate the Handler entry parameter, and start Handler (Controller). Depending on your configuration, Spring will do some extra work for you during the entry process of populating the Handler: When the Handler(Controller) completes execution, it returns a ModelAndView object to the DispatcherServlet;

  • HttpMessageConveter: Converts the request message (such as Json or XML data) into an object, which is converted into the specified response information.
  • Data transformation: Data transformation of the request message. Such as String to Integer, Double, and so on.
  • Data root: Data formatting of the request message. For example, converting a string to a formatted number or a formatted date.
  • Data validation: Verifies the validity of data (length, format, etc.) and stores the validation results in BindingResult or Error.

2.5. According to the returned ModelAndView, select a suitable ViewResolver (must be a ViewResolver registered in the Spring container) and return it to the DispatcherServlet.

2.6. ViewResolver combines Model and View to render the View.

2.7. The view is responsible for returning the render results to the client.

3. Introduce WebApplicationContext

WebApplicationContext is an extension of ApplicationContext. It has some additional functionality required for Web applications. It differs from a normal ApplicationContext in its ability to resolve topics and decide which servlet to associate with.

Vii. On transaction control

A transaction is a sequence of actions that, taken together, constitute a complete unit of work. These actions must all be completed, and if one fails, the transaction rolls back to its original state as if nothing had happened.

1.1 in the spring transaction control API PlatformTransactionManager interfaces provide transaction operation methods, contains three specific operations

public interface PlatformTransactionManager extends TransactionManager {
    // Get transaction status information
    TransactionStatus getTransaction(@Nullable TransactionDefinition var1) throws TransactionException;

    // Commit the transaction
    void commit(TransactionStatus var1) throws TransactionException;

    // Rollback the transaction
    void rollback(TransactionStatus var1) throws TransactionException;
}
Copy the code

Common implementation classes for development:

. Org. Springframework. JDBC datasource. DataSourceTransactionManager: using Spring JDBC or iBatis for persistent dataCopy the code

Structure of the transaction control interface in Spring 1.1.2 TransactionDefinition

The transaction definition information object contains the following methods:

Get transaction object name: String getName()

Get transaction isolation level: int getIsolationLevel()

Int getPropagationBehavior()

Get transaction timeout: int getTimeout()

Boolean isReadOnly()

1.1.3 TransactionStatus

Represents the state information of a transaction object at a point in time, including six specific operations:

Flush transactions: void flush()

HasSavepoint () : Boolean hasSavepoint()

Get transaction completed: Boolean isCompleted()

Get whether transaction is new: Boolean isNewTransaction()

Boolean isRollbackOnly()

Set transaction rollback: void set RollbackOnly()

1.2 Transaction isolation level

The isolation boundary of a transaction reflects the attitude of the transaction when it is committed for concurrent access

1.2.1 Transaction isolation level

  • ISOLATION_DEFAULT Default level. The isolation level is determined by the default Settings of the DBA and belongs to one of the following
  • ISOLATION_READ_UNCOMMITTED is when a transaction can read data from another uncommitted transaction. Dirty reads, unrepeatable reads, phantom reads (lowest isolation level, high concurrency)
  • ISOLATION_READ_COMMITTED is when a transaction waits for another transaction to read data to solve the dirty read problem. Unrepeatable read, phantom read (lock row being read, Oracle default level, on most systems)
  • ISOLATION_REPEATABLE_READ is a solution to the problem of unrepeatable reads, in which no modification operation is allowed once data is read (transaction is started). Phantom read problem (lock all rows read, MYSQL default level)
  • ISOLATION_SERALZABLE is the highest transaction isolation level, at which transactions are sequentially executed to avoid dirty reads, unrepeatable reads, and phantom reads. However, this transaction isolation level is inefficient and costly to database performance, and is generally not used.

The transaction isolation level increases from top to bottom. The higher the isolation level, the more data integrity and consistency are ensured. However, the consumption of database performance increases and the concurrent execution efficiency decreases.

The default isolation level for most databases is Read Commited, such as SqlServer and Oracle

For a few databases, the default isolation level is Repeatable Read. For example, MySQL InnoDB

1.2.2 Three kinds of problems in database reading

① Dirty reads: reads Dirty data.

That is, if uncommitted (and still cached) data from transaction A is read by transaction B, if transaction A fails to roll back, transaction B will read the wrong data.

② Non-repeatable reads: Data cannot be read repeatedly.

For example, transaction A reads the value of price at two places. On the first read, price is 100, and then transaction B changes price to 200; Transaction A reads it again and finds that the price has changed to 200, causing transaction A’s data to be scrambled.

③ Phantom reads: Phantom reads data.

This is similar to non-repeatable reads, which is also a problem of multiple reads being inconsistent in the same transaction. But non-repeatable reads are inconsistent because the data it reads has been changed (such as price) while phantom reads are inconsistent because its conditional data set has been changed.

For example, run the Select account.id where account.name=”Bruce*” command. On the second read, transaction B changed the name of an account from “DD” to “Bruce1”, resulting in seven data fetched.

The emphasis of non-repeatable read is to modify: the same condition, two read values are not the same;

The key of magic reading is to add or delete: the number of records obtained is different between the two reads under the same condition

1.2.3 Correlation between data isolation levels and problems

1.3 Propagation behavior of transactions

  • REQUIRED: Create a new transaction if there are no existing ones, and join one if it already exists. General selection (default)

  • SUPPORTS the current transaction. If there is no transaction, it will be executed in a non-transaction manner (no transaction)

  • MANDATORY: The current transaction is used, and an exception is thrown if no transaction is currently available.

  • REQUERS_NEW: Create a new transaction, or suspend the current transaction if it is currently in one.

  • NOT_SUPPORTED: Performs an operation in a non-transactional manner and suspends the current transaction if one exists.

  • NEVER: runs non-transactionally and throws an exception if a transaction currently exists.

  • NESTED: If a transaction currently exists, it is executed within a NESTED transaction. If there are no transactions currently, something like REQUIRED is performed.

1.4 Timeout Period

Indicates the maximum amount of time that a transaction can wait after it is committed. If the transaction is delayed, it will automatically fail. The default value is -1 and there is no time limit. If yes, set the parameter in seconds.

1.5 Whether it is a read-only transaction

Read-write transactions: enable transactions when adding, deleting, or modifying

Read-only transactions: Transactions are also enabled when the query is executed

Conclusion:

These are almost the core knowledge points of Spring. They are all summaries of concepts and principles, and the specific practical links need to be sorted out slowly. Spring as we have used a framework for development, the impact on us is great, I hope this article is useful to you.

Finally, for everyone’s study and interview review, I have also sorted out quite a lot of interview materials, there are also interviews of other big factories. I hope I can help you.

The answers to the following interview questions are documented in notes. Also sorted out some interview materials & the latest 2020 collection of some big factory interview real questions (are sorted into a document, a small part of the screenshots), there is a need to click into the code nuggets