Java interview summary summary, including Java key knowledge, as well as common open source framework, welcome to read. The article may have wrong place, because individual knowledge is limited, welcome everybody big guy to point out! The article continues to be updated at……

ID The title address
1 Design Mode Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
2 Java Basics (most comprehensive interview questions) Juejin. Cn/post / 684490…
3 Java Set interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490…
4 JavaIO, BIO, NIO, AIO, Netty Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
5 Java Concurrent Programming Interview questions (most comprehensive interview questions) Juejin. Cn/post / 684490…
6 Java Exception Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490…
7 Java Virtual Machine (JVM) Interview Questions Juejin. Cn/post / 684490…
8 Spring Interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490…
9 Spring MVC Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490…
10 Spring Boot Interview Questions (Most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
11 Spring Cloud Interview Questions (The most comprehensive interview questions) Juejin. Cn/post / 684490…
12 Redis Interview Questions (most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
13 MyBatis Interview Questions (most comprehensive interview questions) Juejin. Cn/post / 684490…
14 MySQL Interview Questions (most comprehensive interview questions) Juejin. Cn/post / 684490…
15 TCP, UDP, Socket, HTTP interview questions Juejin. Cn/post / 684490…
16 Nginx Interview Questions (The most comprehensive interview Questions) Juejin. Cn/post / 684490…
17 ElasticSearch interview questions
18 Kafka interview questions
19 RabbitMQ interview questions (most comprehensive summary of interview questions) Juejin. Cn/post / 684490…
20 Dubbo Interview Questions (the most comprehensive interview questions) Juejin. Cn/post / 684490…
21 ZooKeeper Interview Questions Juejin. Cn/post / 684490…
22 Netty Interview Questions (Most comprehensive summary of interview questions)
23 Tomcat Interview Questions (The most comprehensive interview questions) Juejin. Cn/post / 684490…
24 Linux Interview Questions (Most comprehensive Summary of interview questions) Juejin. Cn/post / 684490…
25 Internet Related interview Questions (the most comprehensive summary of interview questions)
26 Internet Security Questions (Summary of the most comprehensive interview questions)

Summary of the Spring

What is spring?

  • Spring is a lightweight Java development framework originally created by Rod Johnson to address the coupling of the business logic layer and other layers of enterprise application development. It is a layered JavaSE/JavaEE full-stack 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.

  • Spring’s fundamental mission is to address the complexities of enterprise application development by simplifying Java development.

  • Spring can do a lot of things, and it provides rich functionality for enterprise development, but the underlying functionality is dependent on its two core features, dependency injection, DI) and aspect-oriented Programming (AOP).

To reduce the complexity of Java development, Spring has adopted four key strategies

  • Pojo-based lightweight and least intrusive programming;
  • Loose coupling through dependency injection and interface oriented;
  • Declarative programming based on aspects and conventions;
  • Reduce boilerplate code with cuts and templates.

Spring has two core concepts

  • IOC (Control flip) :

    • Control rollover, also known as dependency injection, doesn’t create objects directly, it just declares them, it doesn’t connect directly to objects and services in the code, but it describes in the configuration file which components require which services, and the container assembles them. In a normal IOC scenario, the container creates all the objects, sets the required properties to link them together, and then declares them when they need to be used. Annotations are convenient, and the container automatically groups the objects according to the annotations
  • AOP (Faceted programming)

    • Faceted programming, a programming pattern that allows programmers to modularize through custom crosscutting points, encapsulating behaviors that affect multiple classes into reusable modules. Example: For logging output, without AOP you would need to put logging statements in all classes and methods, but with AOP you can wrap logging statements in a reusable module that places them declaratively in a class and automatically completes logging output each time you use the class.

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

  • Spring design goals: Spring provides a one-stop lightweight application development platform for developers;

  • Spring design concept: In JavaEE development, support POJO and JavaBean development methods, make the application interface oriented development, fully support OOP (object-oriented) design method; Spring implements object coupling relationship management through IOC container, and realizes dependency inversion. The dependencies between objects are handed over to IOC container to achieve decoupling.

  • The core of the Spring framework: the IOC container and AOP modules. Managing POJO objects and coupling between them through the IOC container; Enhance services in a dynamic, non-intrusive manner through AOP.

  • IOC allows components that work together to remain loosely coupled, while AOP programming allows you to separate functionality across application layers into reusable functional components.

What are the advantages and disadvantages of Spring?

advantages

  • Easy to decouple and simplify development

    Spring is a big factory that manages the creation of all objects and the maintenance of dependencies.

  • Support for AOP programming

    Spring provides section-oriented programming, which can facilitate the implementation of programs for permission interception, running monitoring and other functions.

  • Support for declarative transactions

    Transactions can be managed through configuration without manual programming.

  • Convenient program testing

    Spring support for Junit4 makes it easy to test Spring programs with annotations.

  • Easy integration of various excellent frameworks

    Spring does not exclude good open source frameworks and provides direct support for them internally (e.g. Struts, Hibernate, MyBatis, etc.).

  • Reduce the difficulty of using JavaEE apis

    Spring provides a wrapper around some of the apis (JDBC, JavaMail, remote calls, etc.) that are very difficult to use in JavaEE development, making these apis much easier to use.

disadvantages

  • Spring is a very lightweight framework, but it feels big and complete
  • Spring relies on reflection, which affects performance
  • With a higher threshold, getting started with Spring takes a long time

What are the applications of Spring

  • Application scenario: JavaEE enterprise application development, including SSH and SSM

Spring value:

  • Spring is a non-invasive framework that aims to minimize application code dependency on the framework;
  • Spring provides a consistent programming model that allows applications to be developed directly using POJOs, isolated from the runtime environment.
  • Spring drives a shift in application design toward object-oriented and interface-oriented development, improving code reuse and testability;

What modules does Spring consist of?

  • In total, Spring has about 20 modules, made up of more than 1,300 different files. And these components are integrated separately inCore ContainerAspect Oriented Programming and Device Support (AOP)Data Access/IntegerationWeb,MessagingTestEtc in 6 modules. Here is the module structure diagram for Spring 5:
  • Spring Core: Provides the basic components of the framework, including Inversion of Control (IOC) and Dependency Injection (DI) capabilities.
  • Spring Beans: Provides a BeanFactory, a classic implementation of the factory pattern, where Spring calls managed objects beans.
  • Spring Context: A context wrapper built on top of the core wrapper that provides a framework for accessing objects.
  • Spring JDBC: Provides a JDBC abstraction layer that simplifies JDBC by eliminating cumbersome JDBC coding and database vendor-specific error code parsing.
  • Spring AOP: Provides a section-oriented programming implementation that lets you customize interceptors, pointcuts, and so on.
  • Spring Web: Provides integrated features for Web development, such as file uploads, Ioc container initialization using Servlet Listeners, and Web ApplicationContext.
  • Spring test: Supports unit and integration testing of Spring components using JUnit or TestNG.

What design patterns are used in the Spring framework?

  1. Factory pattern: BeanFactory is an embodiment of the simple factory pattern, used to create instances of objects;
  2. Singleton mode: Beans default to singleton mode.
  3. Proxy mode: Spring’s AOP features use JDK dynamic proxies and CGLIB bytecode generation techniques;
  4. Template method: Used to solve the problem of code duplication. RestTemplate, JmsTemplate, JpaTemplate.
  5. Observer mode: Defines a one-to-many dependency between object keys. When an object’s state changes, all dependent objects are notified to be updated, as in Spring’s implementation of listener – ApplicationListener.

Take a closer look at the core Container (Spring Context application Context) module

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

  • The Bean factory is an implementation of the factory pattern that provides inversion of control to separate application configuration and dependencies from the actual application code. The most commonly used is org. Springframework. Beans. Factory. XML. XmlBeanFactory, it according to the loading beans defined in the XML file. The container reads configuration metadata from an XML file and uses it to create a fully configured system or application.

What are the different types of events in the Spring framework

  • Spring provides the following five standard events:
    1. Context update events (ContextRefreshedEvent) : in the call ConfigurableApplicationContext interface the refresh () method is triggered.
    2. Context Start event (ContextStartedEvent) : when the container calls ConfigurableApplicationContext Start () method of Start/restart container is triggered when the event.
    3. Context Stop events (ContextStoppedEvent) : when the container calls ConfigurableApplicationContext Stop () method to Stop container is triggered when the event.
    4. ContextClosedEvent: Triggered when ApplicationContext is closed. When the container is closed, all singleton beans it manages are destroyed.
    5. Request processing event (RequestHandledEvent) : In a Web application, this event is triggered when an HTTP request ends. If a bean implements the ApplicationListener interface, the bean is automatically notified when an ApplicationEvent is published.

What are the different components of a Spring application?

Spring applications typically have the following components:

  • Interface – Defines functions.
  • Bean class – it contains properties, setter and getter methods, functions, and so on.
  • Bean configuration file – contains information about the classes and how to configure them.
  • Spring Tangential Programming (AOP) – Provides tangential programming capabilities.
  • User program – it uses interfaces.

What are some ways to use Spring?

Spring can be used in the following ways:

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

Spring Inversion of Control (IOC)

What is the Spring IOC container?

  • Inversion of Control (IOC of Control), which transfers the right to call the object which is controlled by the program code directly to the container, and implements the assembly and management of object components through the container. The concept of “inversion of control” is the transfer of control over a component object from the program code itself to an external container.

  • Spring IOC is responsible for creating objects, managing them (through dependency injection (DI), assembling them, configuring them, and managing their entire life cycle.

What does inversion of control (IOC) do

  • Create managed objects and maintain their dependencies. Object creation is not a simple task, and when object relationships are more complex, it can be quite a headache if the dependencies need to be maintained by the programmer

  • Decoupled, leaving the container to maintain the concrete objects

  • Hosting the class generation process, for example, we need to do some processing in the class generation process, the most direct example is the proxy, if there is a container can hand this part of the processing to the container, the application does not care about how the class does the proxy

What are the advantages of IOC?

  • IOC or dependency injection minimizes the amount of code in your application.
  • It makes applications easy to test, eliminating the need for singletons and JNDI lookups for unit tests.
  • Loose coupling is possible with minimal cost and intrusion.
  • The IOC container supports hunger-style 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(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

What features does Spring’s IOC support

  • Spring’s IOC design supports the following features:

  • The most important of these is dependency injection, which, in XML configuration terms, is the REF tag. Corresponds to the Spring RuntimeBeanReference object.

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

What’s the difference between BeanFactory and ApplicationContext?

  • BeanFactory and ApplicationContext are two core Spring interfaces that can be used as Spring containers. ApplicationContext is the subinterface of the BeanFactory.

  • dependencies

    • BeanFactory: Is the lowest level interface in Spring. It contains the definition of various beans, reads Bean configuration documents, manages Bean loading and instantiation, controls Bean life cycle, and maintains the dependency relationship between beans.
  • The ApplicationContext interface, a derivative of the BeanFactory interface, provides more complete framework functionality in addition to the functionality of the BeanFactory:

    • Inheriting MessageSource, thus enabling internationalization.

    • Unified access to resource files.

    • Provides events to register beans in listeners.

    • Load multiple configuration files simultaneously.

    • Load multiple (inheritable) contexts so that each one focuses on a specific layer, such as the Web layer of the application.

  • Loading way

    • BeanFactroy uses lazy loading to inject beans, meaning that a Bean is loaded and instantiated only when it is used (by calling getBean()). This way, we won’t be able to find some existing Spring configuration issues. If a property of the Bean is not injected, the BeanFacotry load does not throw an exception until the first use of the getBean method.

    • ApplicationContext, which creates all the beans at once when the container is started. This way, we can find configuration errors in Spring when the container starts, which makes it easier to check whether the dependent properties are injected. By preloading singleton beans after the ApplicationContext starts, you ensure that you don’t have to wait for them to be created when you need them.

The only disadvantage of the ApplicationContext relative to the basic BeanFactory is that it takes up memory. When an application has many configured beans, the application starts slowly.

  • Create a way

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

    • BeanFactory and ApplicationContext both support the use of BeanPostProcessor and BeanFactoryPostProcessor, but the difference between them is: BeanFactory needs to be registered manually, whereas ApplicationContext is automatically registered.

How does Spring design the BeanFactory and ApplicationContext context

  • Spring author Rod Johnson designed two interfaces to represent containers.

    • BeanFactory
    • ApplicationContext
  • A BeanFactory is simply a HashMap where the Key is a BeanName and the Value is a Bean instance. Usually, only register (PUT) and get (get) functions are provided. We can call this a “low-level container.”

  • ApplicationContext can be called a high-level container. Because it has more features than BeanFactory. He inherits multiple interfaces. So it has more functions. For example, resource fetching, support for multiple messages (such as JSP tag support), and tool-level support for BeanFactory waiting. So its name is no longer a BeanFactory or something, but an “application context”, which stands for all the functionality of a large container. This interface defines a refresh method, familiar to anyone reading Spring source code, for refreshing the entire container, that is, reloading/refreshing all beans.

  • Of course, in addition to these two large interfaces, there are other secondary interfaces that I won’t cover here.

  • The relationship between BeanFactory and ApplicationContext

  • In order to more intuitive display “low-level container” and “advanced container” relationship, here by the commonly used ClassPathXmlApplicationContext relationship between UML class to show the whole container level.

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

  • The top one is BeanFactory, and the bottom three are green, which are function extension interfaces, so I won’t expand them here.

  • Look below at the “high-level container” of the subordinate ApplicationContext in pink. It depends on the “low-level container”. This means dependency, not inheritance. It relies on the “low-level container” getBean functionality. High-level containers have more capabilities: support for different information sources, access to file resources, and support for application events (Observer mode).

  • Typically what users see is “high-level containers.” But the BeanFactory is also very useful!

  • The gray area on the left is the “low-level container” that loads only beans and retrieves them. Other advanced features of the container are not available. For example, refresh the Bean factory configuration, lifecycle event callbacks, and so on as shown above.

summary

  • Having said so much, I wonder if you understand Spring IOC? To summarize, IOC is implemented in Spring using only low-level containers. There are two steps:
  1. Load the configuration file, parse it into BeanDefinition and place it in the Map.

  2. When you call getBean, you instantiate the Class object from the BeanDefinition Map and recursively call the getBean method if there are dependencies.

  • This is the IOC of the Spring low-level container (BeanFactory).

  • As for the high-level container ApplicationContext, it contains the functionality of the low-level container, which refreshes the beans of the entire container when it executes the Refresh template method. Also, as a high-level container, it contains too much functionality. In short, he is not just the IOC. It supports different information sources, BeanFactory utility classes, hierarchical containers, access to file resources, event notification, interface callbacks, and more.

What is the usual implementation of ApplicationContext?

  • FileSystemXmlApplicationContext: this container loading beans from an XML file, the definition of XML Bean configuration file the full path name must be provided to the constructor.

  • ClassPathXmlApplicationContext: this container is loaded from an XML file beans definition, here, you need to properly set the classpath because the container will be in the classpath to find bean configuration.

  • 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 large concept that 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. Dependency Injection means that the Dependency relationship between components is determined by the container during the operation 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 provides plain Java methods for the container to determine dependencies.

The 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 task of configuring objects should be left to the IOC container, and the “find resources” logic should be extracted from the application component’s code and handed over to the IOC container. The container is responsible for assembly of components, passing dependent objects to desired objects through properties (setters in Javabeans) or constructors.

What are the advantages of dependency injection

  • Dependency injection is more popular because it is a preferable approach: leaving the container solely responsible for dependent queries, the managed component only needs to expose setter methods of Javabeans or parameter-based constructors or interfaces that allow the container to assemble the object’s dependencies at initialization. Compared with dependent search, its main advantages are as follows:
    • The find location operation is completely independent of the application code.
    • Container independent apis make it easy to use application objects outside of any container.
    • No special interfaces are required, and most objects can be done completely independent of the container.

What are the different types of dependency injection implementations?

  • Dependency Injection is the most popular implementation of IOC at present. Dependency Injection can be divided into Interface Injection, Setter Injection and Constructor Injection. Interface injection has been deprecated since Spring4 due to poor flexibility and ease of use.

  • Constructor dependency injection: Constructor dependency injection is implemented by the container firing the constructor of a class that has a series of parameters, each representing a dependency on another class.

  • Setter method injection: Setter method injection implements setter-based dependency injection by invoking Setter methods of a bean after the bean has been instantiated by calling either a no-argument constructor or a no-argument static factory method.

Constructor dependency injection versus Setter method injection

Constructor injection setter injection
No partial injection Partial injection
Setter properties are not overridden It overrides the setter property
Any changes will create a new instance Arbitrary changes do not create a new instance
This is useful for setting many properties Suitable for setting a small number of properties
  • Both types of dependency can be used, constructor injection and Setter method injection. The best solution is to implement mandatory dependencies with constructor arguments and optional dependencies with setter methods.

Spring Beans

What are Spring beans?

  • Spring Beans are the Java objects that form the backbone of a Spring application. They are initialized, assembled, and managed by the Spring IOC container. The Beans are created from metadata configured in the container. For example, as defined in an XML file.

What does a Spring Bean definition contain?

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

How do I provide configuration metadata to the Spring container? Spring can be configured in several ways

  • There are three important ways to provide configuration metadata to the Spring container.
    • XML configuration file.
    • Annotation-based configuration.
    • Java-based configuration.

What information is contained in the Spring configuration file

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

Spring is based on several ways of injecting BEANS with XML

  1. Set method injection;
  2. Constructor injection:
    1. Set the position of the parameter with index;
    2. Set the parameter type by type.
  3. Static factory 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 produces a new bean instance each time it needs to, 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.

Explains the scope of several beans supported by Spring

The Spring framework supports the following five scopes for beans:

  • Singleton: Beans have only one instance per Spring IOC container.
  • Prototype: A bean definition can have multiple instances.
  • Request: Each HTTP request creates a bean, which is only valid in the Web-based Spring ApplicationContext context.
  • Session: In an HTTP session, one bean definition corresponds to one instance. This scope is valid only in the case of web-based Spring ApplicationContext.
  • Global-session: In a global HTTP session, one bean definition corresponds to one instance. This scope is valid only in the case of web-based Spring ApplicationContext.

Note: The default Spring bean is scoped to Singleton. Using the Prototype scope requires careful consideration, as frequent bean creation and destruction imposes a significant performance overhead.

Are singleton beans in the Spring framework thread-safe?

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

  • Beans in Spring are singleton by default. The Spring framework does not encapsulate singleton beans in multiple threads.

  • In fact, most of the time spring beans are stateless (such as dao classes), all beans are safe to some extent, but if beans are stateful (such as View Model objects), it is up to the developer to keep them thread-safe. The simplest is to change the scope of the bean and change “singleton” to “Prototype” so that the request bean is equivalent to new bean (), so thread-safe.

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

How does Spring handle thread concurrency?

  • In general, only stateless beans can be shared in a multithreaded environment. In Spring, most beans can be declared singleton scoped because Spring uses ThreadLocal to handle non-thread-safe state of some beans to address thread-safe issues.

  • Both ThreadLocal and thread synchronization are designed to solve the problem of conflicting access to the same variable in multiple threads. The synchronization mechanism adopts the “time for space” approach, providing only one variable, different threads need to acquire the lock before accessing, and threads that do not acquire the lock need to queue. ThreadLocal takes a “space for time” approach.

  • ThreadLocal provides a separate copy of variables for each thread, isolating conflicting data access from multiple threads. Since each thread has its own copy of the variable, there is no need to synchronize it. ThreadLocal provides thread-safe shared objects that can encapsulate unsafe variables in ThreadLocal when writing multithreaded code.

Explains the life cycle of beans in the Spring framework

  • In traditional Java applications, the bean life cycle is simple. The bean is instantiated using the Java keyword new, and the bean can then be used. Once the bean is no longer in use, it is automatically garbage collected by Java. In contrast, the life cycle of beans in a Spring container is much more complex. It is important to understand the life cycle of Spring beans properly, because you may want to customize the bean creation process by taking advantage of the extension points Spring provides. The following figure shows a typical lifecycle process for beans to be loaded into a Spring application context.

  • Beans go through several stages in the Spring container from creation to destruction, 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.

Let’s describe the above in detail:

  • Spring instantiates the bean;

  • 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 BeanFactoryAware interface, Spring calls the setBeanFactory() method, passing in the BeanFactory container instance;

  • If the bean implements the ApplicationContextAware interface, Spring calls the setApplicationContext() method, passing in a reference to the bean’s application context;

  • If the bean implements the BeanPostProcessor interface, Spring will call their post – ProcessBeforeInitialization () method;

  • If the beans implement the InitializingBean interface, Spring calls their after-propertiesSet () method. Similarly, if the bean declares an initialization method with initMethod, that method is called;

  • If the bean implements the BeanPostProcessor interface, Spring will call their post – ProcessAfterInitialization () method;

  • At this point, the beans are ready to be used by the application, and they will 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. Similarly, if the bean declares a destroy method with destroy-method, that method will also be 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 until you put something in it. To benefit from Spring's DI(dependency injection), we must assemble our application objects into the Spring container.

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

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

  • The bean tag has two important properties (init-method and destroy-method). With them you can customize your initialization and logout methods. They also have corresponding annotations (@postconstruct and @predestroy).

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

  • In the Spring framework, a bean can be declared as an internal bean when it is only used as an attribute of another bean. Inner beans can be implemented in the same way that setters inject “properties” and constructors inject “construct parameters.” Inner beans are usually anonymous, and their Scope is typically prototype.

How do I inject a Java collection in Spring?

  • Spring provides configuration elements (configuration tags) for the following four collection classes:
This tag is used to assemble repeatable list values.
This tag is used to assemble set values that are not duplicated.
This tag can be used to inject keys and values for any type of key-value pair.
This tag supports injection of key-value pairs whose key and value are both strings.

What is bean assembly?

  • Assembly, or bean assembly, refers to the assembly of 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, setting bean dependencies in configuration files is a good mechanism. The Spring container can automatically assemble beans that cooperate with each other. This means that the container does not need configuration and can handle collaboration between beans automatically through the bean factory. This means that Spring can automatically handle Bean dependencies by injecting them into the Bean Factory. Autowiring can be set up on a per-bean basis or on a specific bean.

Explain the different ways to autowire. What are the ways spring autowire beans?

  • In Spring, objects don’t have to find or create other objects associated with them. The container assigns references to objects that need to cooperate with each other, and Autowire is used to configure the auto-load mode.

  • There are five types of autowiring in the Spring framework XML configuration:

    • No: By default, the bean is assembled by manually setting the ref property without autowiring.

    • ByName: Automatic assembly by bean name, if the property of one bean is the same as the name of another bean.

    • ByType: automatic assembly based on the data type of the parameter.

    • Constructor: Assembly using constructors, and constructor parameters are assembled using byType.

    • Autodetect: Automatic detection, construct if there is a constructor, otherwise byType is used.

What is the process of auto-assembly using @Autowired annotations?

  • Use the @AutoWired annotation to automatically assemble the specified bean. The @autowired annotation needs to be configured in the Spring configuration file before being used, <context:annotation-config />.

  • When to start the spring IOC container automatically loaded with a rear AutowiredAnnotationBeanPostProcessor processor, when a container scanning to @ Autowied, @ when the Resource or @ Inject, The desired bean is automatically found in the IOC container and the properties are assembled for that object. When using @autowired, we first query the container for the bean of the corresponding type:

    • If the query results in exactly one, it assembles the bean to the data specified by @AutoWired;

    • If the query has more than one result, @AutoWired looks it up by name;

    • If the result of the above lookup is empty, an exception is thrown. For the resolution, use required=false.

What are the limitations of autowiring?

  • The limitations of autowiring are:

    • Overwrite: You still need to define dependencies with and configuration, which means you always have to override autoassembly.

    • Primitive data types: You cannot auto-assemble simple properties such as primitive data types, strings, and classes.

    • Fuzzy features: Automatic assembly is less accurate than explicit assembly, and explicit assembly is recommended if possible.

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

  • You can.

The Spring annotations

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

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

  • The @Configuration annotation, for example, is used to mark the definition of a class that can be used as a bean 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.

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

How to start annotation assembly?

  • Annotation assembly is not turned on by default, and in order to use annotation assembly we must configure it in the Spring configuration file<context:annotation-config/>Elements.

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.

@required What are annotations for

  • This annotation indicates that the bean’s property must be set in the configuration, through a bean definition of explicit attribute values or by automatic assembly, if @ Required annotations bean attribute is not set, the container will throw BeanInitializationException. Example:
public class Employee {
    private String name;
    @Required
    public void setName(String name){
        this.name=name;
    }
    public string getName(a){
        returnname; }}Copy the code

What does the @autowired annotation do

  • By default, @AutoWired assembles injection by type, which by default requires that the dependent object must exist (you can set its required property to false). The @AutoWired annotation provides more fine-grained control over where and how autoassembly is done. It is used the same way as @required to modify 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(a){
        returnname; }}Copy the code

The difference between @Autowired and @Resource

  • @autowired and @Resource can be used for: constructors, member variables, Setter methods

  • The difference between @autowired and @Resource is

    • By default, @AutoWired assembles injection by type, which by default requires that the dependent object must exist (you can set its required property to false).

    • By default, @Resource assemples injection by name, and only by type if no bean matching the name can be found.

What are the @qualifier annotations for

  • 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.

What are the @requestMapping annotations for?

  • 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 applies at two levels:
    • Class level: URL of the mapping request
    • Method level: mapping URLS and HTTP request methods

Spring data Access

Explains the object/relational mapping integration module

  • Spring provides ORM modules that allow us to use an object/relational mapping (ORM) tool on top of direct JDBC. Spring supports integration with major ORM frameworks such as Hiberate, JDO, and MyBatis, JPA, TopLink, JDO, OJB, and so on. Spring’s transaction management also supports all of the above ORM frameworks and JDBC.

How can I use JDBC more effectively in the Spring framework?

  • Using the Spring JDBC framework, the cost of resource management and error handling is reduced. So developers only need to write statements and queries to retrieve data from the data. JDBC can also be used more efficiently with the help of a template class provided by the Spring framework called JdbcTemplate

Explains the JDBC abstraction and DAO modules

  • By using THE JDBC abstraction and DAO module, the database code is kept simple and the problems caused by the incorrect shutdown of database resources can be avoided. It provides a unified exception access layer on the error information of various databases. It also leverages Spring’s AOP modules to provide transaction management services to objects in Spring applications.

What does the Spring DAO do?

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

What classes exist in the Spring JDBC API?

  • JdbcTemplate

  • SimpleJdbcTemplate

  • NamedParameterJdbcTemplate

  • SimpleJdbcInsert

  • SimpleJdbcCall

What is the JdbcTemplate

  • The JdbcTemplate class provides convenient methods for converting database data to primitive data types or objects, executing written or callable database operation statements, and providing custom data error handling.

How do YOU access Hibernate using Spring? What are the ways to access Hibernate using Spring?

  • There are two ways to access Hibernate in Spring:
    • Use Hibernate templates and callbacks for inversion of control
    • Extend Hibernateda Support and apply the AOP interceptor node

How to combine Spring and Hibernate with Hibernateda Support?

  • Call LocalSessionFactory with Spring’s SessionFactory. The integration process is divided into three steps:
    • Configure the Hibernate SessionFactory
    • Implement a DAO by inheriting HibernateDaoSupport
    • Assemble in an AOP supported transaction

What transaction management types are supported by Spring, and how are Spring transactions implemented?

  • Spring supports two types of transaction management:
    • Programmatic transaction management: This means you manage transactions programmatically, giving you great flexibility but being difficult to maintain.

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

How and how Spring transactions are implemented

  • The essence of Spring transactions is the transaction support of the database. Without the transaction support of the database, Spring cannot provide transaction functionality. The real database layer commits and rolls back transactions through binlog or redo log.

Talk about Spring’s transaction propagation behavior

The propagation behavior of Spring transactions describes how Spring handles the behavior of multiple transactions when they exist at the same time.

1, PROPAGATION_REQUIRED: Create a new transaction if there is no transaction currently, PROPAGATION_REQUIRED: Join the transaction if there is one, this setting is the most commonly used.

(2) PROPAGATION_SUPPORTS: Supports the current transaction. If a transaction exists, join it, and execute it as a non-transaction if no transaction exists.

③ PROPAGATION_MANDATORY: The current transaction is supported. If a transaction exists, the transaction is added, and if no transaction exists, an exception is thrown.

(4) PROPAGATION_REQUIRES_NEW: Creates a new transaction, regardless of whether one currently exists.

⑤ PROPAGATION_NOT_SUPPORTED: Execute an operation non-transactionally, and suspend the current transaction if it exists.

⑥ PROPAGATION_NEVER: Executes non-transactionally, and throws an exception if a transaction currently exists.

⑦ PROPAGATION_NESTED: Executes within a nested transaction if a transaction currently exists. If there are no transactions currently, the REQUIRED attribute is executed.

What about Transaction isolation in Spring?

  • Spring has five isolation levels, the default being ISOLATION_DEFAULT (using database Settings), and the other four are consistent with database isolation levels:

    1. ISOLATION_DEFAULT: Use the isolation level set by the underlying database, I use whatever the database is set to;

    2. ISOLATION_READ_UNCOMMITTED: The read is not committed, the lowest isolation level, before the transaction is committed, can be read by other transactions (magic read, dirty read, unrepeatable read);

    3. ISOLATION_READ_COMMITTED: Committed reads. A transaction can only be read by other transactions after committed (causing illusory reads and unrepeatable reads). Default level of SQL Server.

    4. ISOLATION_REPEATABLE_READ: repeatable reading, ensuring that the same data is read repeatedly with the same content at the beginning of the transaction. It is forbidden to read data not committed by other transactions (causing phantom reads). Default level of MySQL.

    5. ISOLATION_SERIALIZABLE: Serialization, the most expensive and reliable isolation level that prevents dirty reads, unrepeatable reads, and phantom reads.

  • Dirty read: Indicates that one transaction can read data that has not yet been committed in another transaction. For example, A transaction may attempt to insert record A before the transaction commits, and then another transaction may attempt to read record A.

  • Non-repeatable read: the same data is read multiple times in a transaction.

  • Phantom read: When multiple queries within the same transaction return different result sets. For example, the same transaction A has N records in the first query, but n+1 records in the second query under equal conditions. This is like hallucination. Phantom reading occurs when another transaction adds or deletes or modifies data in the result set of the first transaction. When the data content of the same record is modified, all data rows become more or less.

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

  • Provides an unchanging programming pattern for different transaction apis such as JTA, JDBC, Hibernate, JPA and JDO.
  • Provides a simple SET of apis for programmatic transaction management rather than complex transaction apis
  • Support for declarative transaction management.
  • Integrates well with Spring’s various data access abstraction layers.

Which transaction management style do you prefer?

  • Most users of the Spring framework opt for declarative transaction management because it has the least impact on application code and is therefore more in line with the idea of a lightweight container with no intrusion. Declarative transaction management is superior to programmatic transaction management, although it is less flexible than programmatic transaction management, which allows you to control transactions through code. The only downside is that the maximum granularity applies only at the method level, not at the code block level like programmatic transactions.

Spring Faceted Programming (AOP)

What is the AOP

  • Object-oriented Programming (OOP) allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships, resulting in a lot of code repetition, and is not conducive to the reuse of each module.

  • Aspect-oriented Programming (AOP), commonly known as Aspect Oriented Programming, is a supplement to object orientation. AOP is used to extract and encapsulate the common behavior and logic that is irrelevant to business but affects multiple objects into a reusable module. This module, named Aspect, reduces duplicate code in the system, reduces coupling between modules, and improves system maintainability. It can be used for permission authentication, logging, and transaction processing.

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

  • The key of AOP implementation lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy. Static proxies are represented by AspectJ; Dynamic proxies are represented by Spring AOP.

    • (1) AspectJ is an enhancement to static proxies. Static proxies are the AOP framework that generates AOP proxy classes at compile time, so it is also called compile-time enhancement. It will weave AspectJ(aspects) into Java bytecode at compile time and run as enhanced AOP objects.

    • (2) Spring AOP use dynamic proxy, the so-called dynamic proxy is an AOP framework won’t go to modify the bytecode, but each time to run in memory temporarily for the method to generate a AOP object, the object of AOP method contains all of the target object, and in particular the tangent point of enhancement processing, and the correction method of the original object.

Differences between JDK dynamic proxies and CGLIB dynamic proxies

  • There are two main types of dynamic proxies in Spring AOP, JDK dynamic proxies and CGLIB dynamic proxies:

    • JDK dynamic proxies only provide proxies for interfaces, not classes. The core InvocationHandler interface and Proxy class, InvocationHandler invokes code in the target class through the invoke() method reflection, dynamically weaving crosscutting logic and business together; Next, the Proxy uses InvocationHandler to dynamically create an instance that conforms to an interface, generating a Proxy object for 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 Code Generation Library that can dynamically generate a subclass object of a specified class at runtime, and override specific methods and add enhanced Code to implement AOP. CGLIB is dynamically proxied by inheritance, so if a class is marked final, it cannot be dynamically proxied using CGLIB.

  • Static proxies differ from dynamic proxies in the timing of the generation of AOP proxy objects. AspectJ’s approach to static proxies has better performance, but AspectJ requires a specific compiler for processing, whereas Spring AOP does not.

Invoke (Object Proxy,Method Method,Object[] args) of InvocationHandler: Proxy is the final generated proxy instance; Method is a specific method of the proxied target instance; Args is a concrete entry to a method of the propped target instance that is used when the method reflection is invoked.

Explain some terms in Spring AOP

  • (1) Aspect: Aspect is the combination of notification and pointcut. Together, notifications and pointcuts define the entire content of the aspect. In Spring AOP, aspects can be implemented using generic classes (pattern-based styles) or in ordinary classes with @AspectJ annotations.

  • (2) Join point: refers to method. In Spring AOP, a Join point always represents the execution of a method. Applications may have thousands of times to apply notifications. These moments are called connection points. A join point is a point at which an aspect can be inserted during application execution. This point can be when a method is called, when an exception is thrown, or even when a field is modified. These points can be used by aspect code to plug into the normal flow of your application and add new behavior.

  • (3) Advice: In AOP terminology, aspect work is called Advice.

  • (4) Pointcut: The definition of the Pointcut matches one or more join points into which the advice is woven. We usually specify these pointcuts using either explicit class and method names, or regular expressions that define matching class and method names.

  • 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 adviced object. Since Spring AOP is implemented through a runtime proxy, this object is always a proxied object.

  • Weaving: Weaving is the process of applying a slice 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: The aspect is woven in when the target class is compiled. AspectJ’s weaving compiler weaves facets in this way.
    • Class loading time: The aspect is woven when the target class is loaded into the JVM. Special class loaders are required that enhance the bytecode of the target class before it is introduced into the application. AspectJ5’s load-time weaving supports weaving into facets in this way.
    • Run-time: Facets are woven in at some point during the application run. Typically, the AOP container dynamically creates a proxy object for the target object when weaving into the cut. SpringAOP is woven into the facets in this way.

Spring notifies objects at run time

  • Spring weaves the aspects into spring-managed beans at run time by wrapping them in a proxy class. The proxy encapsulates the target class, intercepts the invocation of the notified method, and forwards the invocation to the actual target bean. When the proxy intercepts a method call, the aspect logic is performed before calling the target bean method.

  • Spring does not create a proxy object until the bean that needs to be proxied is applied. If you use the ApplicationContext, Spring creates the proxied object only when the ApplicationContext loads all the beans from the BeanFactory. Since the Spring runtime only creates proxy objects, we don’t need a special compiler to weave into SpringAOP’s facets.

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. Join point interception capabilities outside of methods that we can complement with aspects.

What is the difference between concerns and crosscutting concerns in Spring AOP? The difference 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 we want to implement.

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

What are the types of Spring notifications?

  • In AOP terminology, aspect work is called advice and is actually a piece of code that is triggered by the SpringAOP framework when a program executes.

  • Spring facets can apply five types of notifications:

    1. Before: call notification Before the target method is called;
    2. After notification: the notification is called After the target method has completed, regardless of what the output of the method is.
    3. Post-returning notification: notification is called After successful execution of the target method;
    4. After-throwing: calls notifications After the target method throws an exception;
    5. Around advice: Advice wraps the notified method, performing custom behavior before and after the notified method invocation.

What is a sectional Aspect?

  • An aspect consists of pointcount and advice, and a section is a combination of advice and pointcuts. It includes both the definition of crosscutting logic and the definition of join points. Spring AOP is the framework responsible for implementing the aspect, weaving the crosscutting logic defined by the aspect into the join points specified by the aspect. AOP’s focus is on how to enhance the join points of the woven target objects, which consists of two tasks:

    • How do I locate a specific JoinPoint using pointcut and advice
    • How to write aspect code in advice.
  • It is easy to think of a class annotated with @aspect as an Aspect.

Explains the implementation of aspects based on XML Schema

  • In this case, the facets are implemented by regular classes as well as XML-based configurations.

Explains annotation-based aspect implementations

  • In this case (based on the @AspectJ implementation), the style of aspect declarations involved is consistent with normal Java classes with Java5 annotations.