What is the Spring Framework

Spring official website: spring. IO /.

It is a collection of modules that can be used to facilitate development. These modules are: core container, data access/integration, Web, AOP (aspect oriented programming), tools, messaging, and test modules. For example, the Core component in Core Container is the Core of all Spring components, the Beans component and Context component are the basis for IOC and dependency injection, and the AOP component is used to implement tangential programming.

  • Core technologies: Dependency Injection (DI), AOP, Events, Resources, I18N, validation, data binding, type conversion, SpEL.
  • Testing: Mock objects, TestContext framework, Spring MVC tests, WebTestClient.
  • Data access: transaction, DAO support, JDBC, ORM, marshalling XML.
  • Web support: Spring MVC and Spring WebFlux Web Framework.
  • Integration: remote processing, JMS, JCA, JMX, email, tasks, scheduling, caching.
  • Languages: Kotlin, Groovy, dynamic languages

The advantages of Spring?

  • Spring is a low-intrusion design with minimal code contamination;
  • Spring’s DI mechanism leaves the dependencies between objects to the framework, reducing the coupling of components.
  • Spring provides AOP technology that enables centralized management of common tasks such as security, transactions, logging, permissions, and so on for better reuse.
  • Spring provides integration support for mainstream application frameworks.

Name some important Spring modules?

  • Spring Core: Basic, it can be said that all of Spring’s other functions depend on this library. It mainly provides IoC dependency injection function.
  • Spring Aspects: This module provides support for integration with AspectJ.
  • Spring AOP: Provides a section-oriented programming implementation.
  • Spring JDBC: Java database connection.
  • Spring JMS: Java messaging service.
  • Spring ORM: Used to support ORM tools such as Hibernate.
  • Spring Web: Provides support for creating Web applications.
  • Spring Test: Provides support for JUnit and TestNG tests.

@RestController vs @Controller

Using @controller alone without @responseBody is usually used when you want to return a view, which is a more traditional Spring MVC application, corresponding to the case where the front and back end are not separated.

@RestController =@Controller +@ResponseBody
Copy the code

Talk about your understanding of Spring IoC and AOP

  • IOC

    IoC is a design concept that hands over Control of manually created objects in programs to the Spring framework. IoC is also used in other languages, not specific to Spring. IoC container is the carrier used by Spring to implement IoC. IoC container is actually a Map (key, value), which stores various objects.

    The interdependencies between objects are managed by the IoC container and the object injection is completed by the IoC container. This greatly simplifies application development and frees applications from complex dependencies. The IoC container is like a factory. When we need to create an object, all we need to do is configure the configuration file/annotations, regardless of how the object was created. In a real project, a Service class might have hundreds or even thousands of classes as its underlying class. If we need to instantiate the Service, you might have to figure out the constructors of all the underlying classes of the Service every time, which can drive people crazy. With IoC, all you need to do is configure it and then reference it where you need it, which makes your project much more maintainable and easier to develop.

  • AOP

    AOP(aspect-oriented Programming: section-oriented Programming) can encapsulate the logic or responsibility (such as transaction processing, log management, permission control, etc.) that has nothing to do with business but is called jointly by business modules, so as to reduce the repeated code of the system and reduce the coupling degree between modules. And is conducive to the future scalability and maintainability.

    Spring AOP is based on dynamic proxies. If you want to Proxy an object that implements an interface, Spring AOP uses JDK Proxy to create Proxy objects. If you don’t implement an interface, you can’t use JDK Proxy to Proxy objects. In this case, Spring AOP uses Cglib, which generates a subclass of the proxied object as the proxy

What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is runtime enhancement, while AspectJ is compile-time enhancement. Spring AOP is based on Proxying, while AspectJ is based on Bytecode Manipulation.

Spring AOP already integrates with AspectJ, which is arguably the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simple,

If we have fewer cuts, there is not much difference in performance. However, when there are too many facets, AspectJ is the best choice, which is much faster than Spring AOP.

What are the scopes of beans in Spring?

  • Singleton: A unique bean instance. Beans in Spring are singleton by default.
  • Prototype: Each request creates a new bean instance.
  • Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.
  • Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.
  • Global-session: the global session scope, which is only meaningful in portlet-based web applications, is no longer available in Spring5. Portlets are small Java Web plug-ins that can generate snippets of semantic code, such as HTML. They are based on portlet containers and can handle HTTP requests like servlets. However, unlike servlets, each portlet has a different session.

Are beans in Spring thread-safe?

With singleton beans, all threads share a singleton instance Bean, so there is competition for resources.

A singleton Bean is thread-safe if it is a stateless Bean, meaning that operations in a thread do not perform operations other than queries on members of the Bean. For example, Spring MVC’s Controller, Service, Dao, etc., these beans are mostly stateless and only focus on the method itself.

For stateful beans, Spring officially provides a way to handle thread safety through ThreadLocal. Such as RequestContextHolder, TransactionSynchronizationManager, LocaleContextHolder, etc.

The container itself does not provide a thread-safe policy for beans, so it can be said that beans in the Spring container do not have thread-safe features themselves. Therefore, thread-safe depends entirely on the nature of the Bean itself.

What’s the difference between @Component and @Bean?

  1. Different objects:@ComponentAnnotations apply to classes, and@BeanAnnotations apply to methods.
  2. @ComponentIt is usually automatically detected by classpath scanning and automatically assembled into the Spring container (we can use it@ComponentScanThe annotation defines the path to scan for classes that identify the assembly to be automatically assembled into Spring’s bean container.@BeanAn annotation is usually defined to produce the bean in a method marked with the annotation,@BeanTells Spring that this is an example of a class and gives it back to me when I need to use it.
  3. @BeanAnnotations thanComponentAnnotations are more customizable, and there are many places we can only pass@BeanAnnotations to register beans. For example, when we reference a third party library class that needs to be assembled intoSpringContainer, can only pass through@BeanTo implement.

What are the annotations that declare a class as a Spring bean?

We typically use @AutoWired annotation auto-assembly beans. To identify a class as a class that can be used with @AutoWired annotation auto-assembly beans, use the following annotations:

  • @Component: generic annotation that can mark any class asSpringComponents. This can be used if a Bean does not know which layer it belongs to@ComponentAnnotation annotation.
  • @Repository: Corresponds to the Dao layer, which is mainly used for database operations.
  • @Service: Corresponds to the service layer, which mainly involves some complex logic and requires the Dao layer.
  • @Controller: Corresponding to the Spring MVC control layer, the primary user accepts the user request and calls the Service layer to return data to the front-end page.

Bean life cycle in Spring?

  • The Bean container finds the definition of the Spring Bean in the configuration file.
  • The Bean container creates an instance of a Bean using the Java Reflection API.
  • If some attribute values are involved utilizeset()Method sets some property values.
  • If the Bean is implementedBeanNameAwareInterface, callsetBeanName()Method, the name of the Bean passed in.
  • If the Bean is implementedBeanClassLoaderAwareInterface, callsetBeanClassLoader()Method, passed inClassLoaderObject.
  • Similar to the above, if other implementations are implemented*.AwareInterface to invoke the corresponding method.
  • If there is a Spring container associated with loading the BeanBeanPostProcessorObject, executepostProcessBeforeInitialization()methods
  • If the Bean is implementedInitializingBeanInterface, executeafterPropertiesSet()Methods.
  • If the Bean definition in the configuration file contains the init-method attribute, the specified method is executed.
  • If there is a Spring container associated with loading the BeanBeanPostProcessorObject, executepostProcessAfterInitialization()methods
  • When it is time to destroy the Bean, if the Bean is implementedDisposableBeanInterface, executedestroy()Methods.
  • When it is time to destroy a Bean, execute the specified method if the Bean’s definition in the configuration file contains the destroy-method attribute.

How SpringMVC works

  1. The client (browser) sends the request, directly toDispatcherServlet.
  2. DispatcherServletCalled based on the request informationHandlerMappingParse the request corresponding toHandler.
  3. Parse to the correspondingHandlerThat’s what we sayControllerController) after starting fromHandlerAdapterAdapter processing.
  4. HandlerAdapterDepending on theHandlerTo call the real handler to open the request and process the corresponding business logic.
  5. When the processor finishes processing the business, it returns oneModelAndViewObject,ModelIs the returned data object,ViewIt’s a logical oneView.
  6. ViewResolverWill follow logicViewFind the actualView.
  7. DispaterServletThe return ofModelTo pass toViewView rendering.
  8. theViewReturn to the requester (browser)

How many ways does Spring manage transactions?

  1. Programmatic transactions, hard-coded in code. (Not recommended)
  2. Declarative transactions, configured in configuration files (recommended)

Declarative transactions fall into two categories:

  1. Declarative TRANSACTIONS based on XML
  2. Annotation-based declarative transactions

What are the isolation levels in Spring transactions?

  • TransactionDefinition. ISOLATION_DEFAULT: use a backend database default isolation level, Mysql default REPEATABLE_READ isolation level used Oracle READ_COMMITTED) isolation level used by default.
  • TransactionDefinition. ISOLATION_READ_UNCOMMITTED: the lowest isolation level, allowing the read has not yet been submitted data changes, may lead to dirty reads, phantom read or not repeatable read
  • TransactionDefinition. ISOLATION_READ_COMMITTED: allow read of concurrent transactions have to submit data, can prevent dirty reads, but phantom read or not repeatable read could still happen
  • TransactionDefinition. ISOLATION_REPEATABLE_READ: many of the same field to read the results are consistent, unless the data have been modified by itself affairs on their own, can prevent the dirty read and not repeatable read, but phantom read could still happen.
  • TransactionDefinition. ISOLATION_SERIALIZABLE: the highest isolation level, completely obey the ACID isolation level. All transactions are executed one by one so that interference between transactions is completely impossible. That is, this level prevents dirty reads, unrepeatable reads, and phantom reads. But this severely affects the performance of the program. This level is also not typically used.

What kinds of transaction propagation behavior do Spring transactions have?

Cases that support the current transaction:

  • TransactionDefinition. PROPAGATION_REQUIRED: if a transaction exists, then join the transaction; If there is no transaction currently, a new transaction is created.
  • TransactionDefinition. PROPAGATION_SUPPORTS: if a transaction exists, then join the transaction; If there is no transaction currently, it continues in a non-transactional manner.
  • TransactionDefinition. PROPAGATION_MANDATORY: if a transaction exists, then join the transaction; If there is no transaction currently, an exception is thrown. (Mandatory: mandatory)

The current transaction is not supported:

  • TransactionDefinition. PROPAGATION_REQUIRES_NEW: create a new transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NOT_SUPPORTED: run way of transaction, if a transaction exists, suspending the current transaction.
  • TransactionDefinition. PROPAGATION_NEVER: run way of transaction, if the current transaction, throw an exception.

Other information:

  • TransactionDefinition. PROPAGATION_NESTED: if a transaction exists, then create a transaction for the current affairs of nested transactions to run; If no current affairs, the value of equivalent to the TransactionDefinition. PROPAGATION_REQUIRED.

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.

  1. 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:

① Inherits MessageSource and therefore supports internationalization.

② Unified access mode of resource files.

③ Provide the event to register the bean in the listener.

4. Load multiple configuration files at the same time.

(5) Load multiple (inheritable) contexts so that each context is focused on a specific layer, such as the web layer of the application.

  1. BeanFactroy uses lazy loading to inject beans. That is, the BeanFactroy is loaded and instantiated only when it is used (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.

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

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

<! Check that your CellPhone is deployed to the prototype scope --> <bean ID ="cellPhone" class="com.abc.CellPhone" scope="prototype" />
<bean id="developer" class="com.abc.Developer"> <! -- getPhone returns CellPhone. Each call gets new CellPhone --> <lookup-method name="getPhone" bean="cellPhone" />
</bean>
  
  public class CellPhone implements Phone {
    public CellPhone() {
        System.out.println("Spring instantiates dependent beans... CellPhone cases");
    }
    public return call() {
        return "On the phone...";
    }
}

  public abstract class Developer implements Person {
    public Developer() {
        System.out.println("Spring instantiates the calling Bean... Developer instance"); } // Define an abstract method that Spring will implement public abstract Phone getPhone(); @Override public voidcall() {
        System.out.println("In use" + getPhone() + "Make a call");
        System.out.println(getPhone().call());
    }
}

  public class Test {
    public static void main(String args[]) {
        ApplicationContext context = 
                new ClassPathXmlApplicationContext("applicationContext.xml");
        Developer d = context.getBean("developer", Developer.class); d.call(); d.call(); }}Copy the code

The applicationgContext. XML file defines a bean with the id of authService. This bean is obtained through the getBean method of the ApplicationContext instance object.

When the Spring container starts, it parses applicationgContext.xml to parse beans defined in the XML (such as authService) into Spring’s internal BeanDefinition. With beanName(for example, authService) as the key, BeanDefinition (such as authService corresponding BeanDefinition) as the value stored in the DefaultListableBeanFactory beanDefinitionMap of attributes (in fact it is a Concurrent Attribute of type HashMap), storing beanName in beanDefinitionNames (type List), then iterating beanName for beanDefinitionNames, instantiating the bean and populating the properties. During the instantiation, If a dependency is not instantiated, the dependency is instantiated first, and then the dependency itself is instantiated. After the instantiation, the instance is stored in the cache of the singleton bean. When the getBean method is called, the singleton bean is searched in the cache. Then you can use it directly.

What is the process of parsing an XML file?

Specified in the code to load the XML file, after the Spring container in the process of initialization, through ResourceLoader interface implementation class, ClassPathXmlApplicationContext, for example, to convert the XML file path to the corresponding Resource file, For example, the ClassPathResource file is converted to a Document file using the DocumentLoader. Then through DefaultBeanDefinitionDocumentReader to parse the Document, and use BeanDefinitionParserDelegate to parse element to parse the XML bean definitions in each element, Put it in the BeanDefinition.

So what is this BeanDefinition?

In order for the life cycle of an object to be managed by the Spring container, its class information must first be translated into Spring’s internal data structure. BeanDefinition is the data structure used by the Spring framework to describe the class information of the object. For example, class name, scope, attribute, constructor parameter list, dependent bean, whether it is a singleton class, whether it is lazy loading, etc. In fact, the definition information of the bean is stored in the corresponding attribute of the BeanDefinition, and then the operation on the bean is performed directly on the BeanDefinition. For example, once you have the BeanDefinition, you can use reflection to create an object based on the class name, constructor, and constructor parameters. BeanDefinition is an interface. It is an abstract definition that actually uses its implementation classes, such as ChildBeanDefinition, RootBeanDefinition, GenericBeanDefinition, and so on. BeanDefinition inherits AttributeAccessor, which means it has the ability to process attributes. BeanDefinition inherits BeanMetadataElement, which means that it can hold a Bean metadata element that holds an Object corresponding to a Bean tag in an XML file.

Just you have said to DefaultListableBeanFactory, what is the role of it in the Spring framework?

DefaultListableBeanFactory is the core part of the Bean loading, it is Spring registration and load the default implementation of the Bean. DefaultListableBeanFactory indirectly realized the BeanFactory interface, and in the BeanFactory interface defines the bean and many operations related methods, such as getBean, containsBean, isSingleton etc., So DefaultListableBeanFactory also hold the operation accordingly.

What’s the BeanFactory?

BeanFactory is the root interface used to access the Spring Bean container. It is a pure Bean factory, often referred to as the top definition of the IOC container, on which various IOC containers have been extended to meet different requirements, including the frequently used ApplicationContext.

How to understand BeanFactory and FactoryBean?

The BeanFactory defines the most basic form of the IOC container and provides the most basic interface that the IOC container complies with. This is the lowest and most basic programming specification that Spring IOC complies with. It is an interface, not an implementation of the IOC container. Its responsibilities include instantiating, locating, configuring objects in an application, and establishing dependencies between these objects. In general, Spring instantiates beans using the bean’s class properties through reflection. However, in some cases, the process of instantiating beans is complicated and requires a lot of configuration information in the bean definition in the traditional way. Spring provides a factory class interface for FactoryBean. You can implement this interface to customize the logic of instantiating the Bean.

If you want to modify the properties of a bean before initialization, how do you do that?

Customize a BeanFactoryPostProcessor that implements the BeanFactoryPostProcessor interface and implements the postProcessBeanFactory method, in which you can modify the bean’s properties before initialization.

How is this custom BeanFactoryPostProcessor automatically invoked?

In the process of the Spring container initialization is automatically triggered, specific code in AbstractApplicationContext will call invokeBeanFactoryPostProcessors method in the class, Filter out all the class names that implement the BeanFactoryPostProcessor interface in this method, and then iterate through the postProcessBeanFactory method that calls those implementation classes.

If you want to intercept a bean while it is being initialized and perform additional initialization operations, how do you do that?

Customize BeanPostProcessor to implement the BeanPostProcessor interface. In this interface, two methods are defined: PostProcessBeforeInitialization and postProcessAfterInitialization. PostProcessBeforeInitialization method before the afterPropertiesSet and custom initialization method, by implementing this method, the method of internal for additional operations before initialization. PostProcessAfterInitialization method after the afterPropertiesSet and custom initialization method, by implementing this method, the method of internal extra operation after initialization.

Will all defined beans be initialized during Spring container initialization?

No, by default, only all uninitialized, non-lazy-loaded singleton beans are initialized. Beans with other scope values are initialized when they are used, as in Prototype.

Have you seen the source code for bean initialization in Spring?

Singleton bean initialization, through reflection to create instance objects, during the property filling, if the dependent object is not created, create the dependent object first, and finally add the bean instance to the cache of the singleton bean instance.

How does Spring address loop dependencies during bean instantiation?

Spring only for singleton bean circular dependencies are solved, at the same time, if is caused by the constructor injection cycles, the Spring is no way to solve, just throw BeanCurrentlyInCreationException anomalies. If it is a circular dependency created by setter injection, Spring creates a bean object by exposing an ObjectFactory in advance to return a bean object that is being created so that other beans can reference the bean.