Java Interview - Spring

1. What is an IOC?

  1. IOC (Inversion Of Control): Inversion of control is a design idea. For spring, it means that the control right to manually create objects in the original program is handed over to the Spring framework for management.
  2. Control: Refers to the power of object creation (instantiation, management)
  3. Inversion: Control is handed over to the external environment (Spring framework, IOC container)

image.png

2. What is AOP?

  1. AOP (Aspect-Oriented Programming): Simply put, it is to extract the same code in some business logic into an independent module to make the business more refreshing.
  2. AOP is based on dynamic proxy. If the interface is implemented, JDK dynamic proxy will be used. Otherwise, CGLIB proxy will be used to process some system-level services with cross-cutting properties, such as log collection, transaction management, security check, and cache. , object pool management
  3. AOP core concepts:
concept name effect
Target Notified object
Proxy The proxy object created after applying the notification to the target object
Join Points The class to which the target object belongs, all methods defined are connection points
Entry point (Pointcut) Junction points intercepted/enhanced by aspects
Advice Enhanced logic/code, that is, what to do after intercepting the connection point to the target object
Aspect Pointcut + Advice
Weaving Applies the notification to the target object, thereby generating the procedural action of the proxy object
  1. For specific usage, please see my other article. Configuring logs for your project (AOP+logback)_wzdhc's Blog-CSDN Blog

3. What is the life cycle of Spring Bean?

The life cycle of beans in Spring IOC is roughly divided into four stages:

  1. instantiate
  2. attribute assignment
  3. initialization
  4. destroy

image.png

This is more detailed, I am a bit of a cook, if this is really asked, there is nothing I can do

4. What will the Spring container do during the startup phase?

  1. The Spring container startup phase can be divided into two phases: 容器启动阶段and Bean实例化阶段.
  2. In fact, the main work of the container startup phase is to load and parse the configuration file, and save it to the corresponding Bean definition.
  3. Detailed process:
    1. Resource Targeting: Targeting Profiles
    2. Resource loading: After positioning, an appropriate parser will be selected to load the configuration file and converted into a data structure inside the container, such as BeanDefinition
    3. BeanDefinition registration: register the obtained BeanDefinition to the internal BeanDefinitionRegistry
    4. Bean instantiation pre-processing: processing through BeanPostProcessor and BeanFactoryPostProcessor, etc.
    5. Bean instantiation: instantiate all beans through constructor injection, factory method injection, etc.
    6. Dependency injection: When the bean is instantiated, the required dependent objects will be injected into the bean
    7. Processing before and after initialization: before and after Bean initialization, the container provides some extensibility points
    8. Bean initialization: call the Bean initialization method
    9. Container is available: the container can be used externally
    10. Container destruction: the program is closed, and the container will call the destruction methods of all beans

5. What is the scope of Spring Bean?

scope effect
singleton There is only one Bean instance in the Spring container, and the Bean exists as a single instance, which is the default scope of the Bean
prototype Every time the bean is called from the container, a new instance is returned
request (only for web) Every http request will generate a new bean, which is only valid within the current HTTPRequest
session (applies to web only) The same http Session shares a bean, and different Http Sessions use different beans

6. How to solve the circular dependency problem?

  1. Circular dependency: it depends on itself, or other beans depend on each other
  2. The steps of bean initialization are divided into: instantiation, property assignment, initialization
  3. Solution: Solve it through the third-level cache
    1. Level 1 cache: singleton pool, the user saves the bean instance that is instantiated, attribute assigned, and initialized
    2. Level 2 cache: early exposure objects, users save instantiated bean instances
    3. L3 cache: early exposure object factory, used to save bean creation factory, so that later extensions have the opportunity to create proxy objects

image.png

7. Tell me the difference between BeanFactory and Factory?

BeanFactory FactoryBean
Is an interface, is a Factory, that is, IOC container or object factory It is an interface, a special bean that can produce or modify the factory bean generated by the object
Instantiate, locate, configure objects in the application and establish dependencies between these objects The logic of customized beans can be realized through this interface, and spring itself provides more than 70 implementations of FactoryBean
Provides the most basic form of the IOC container, and provides specifications for the implementation of specific IOC containers Provides a more flexible way for the implementation of beans in the IOC container, and adds a simple factory pattern and decoration pattern to the implementation of beans on the basis of the IOC container

8. Tell me about the difference between BeanFactory and ApplicationContext?

  1. BeanFactory:
    1. It is the lowest-level interface in Spring, including various bean definitions, reading bean configuration documents, managing bean loading, instantiation, controlling bean life cycle, and maintaining dependencies between beans
    2. The bean is injected in the form of lazy loading
    3. is usually created by becoming
    4. Need to manually register BeanPostProcessor, BeanFactoryPostProcessor
  2. ApplicationContext:
    1. As a derivative of BeanFactory, it has more complete framework functions than BeanFactory
    2. It loads all beans at once in container startup
    3. Occupies a lot of memory space, when the program configures many beans, the startup is full
    4. It can be created by becoming or by declarative
    5. Automatic registration of BeanPostProcessor and BeanFactoryPostProcessor

9. What design patterns are used in Spring?

The design pattern used effect
factory pattern The essence of the Spring container is a large factory, using the factory pattern to create Bean objects through BeanFactory and ApplicationContext
Proxy mode The implementation of Spring AOP function is through proxy mode, which is divided into static proxy and dynamic proxy
singleton pattern The bean in Spring is a singleton by default, which is conducive to the management of the bean by the container
template pattern Template patterns are used in JdbcTemplate, RestTemplate, etc. in Spring
Observer pattern Spring event-driven model is a classic application of observer mode
adapter pattern The enhancement or notification of Spring AOP uses the adapter mode, and the adapter mode is also used in Spring MVC to adapt the Controller
strategy pattern There is an interface Resource interface in Spring, and its different implementation classes will access resources according to different strategies

10. What is MVC in Spring MVC? What are the core components?

  1. MVC: Model (Model), View (View), Controller (Controller).
  2. Spring MVC is an excellent framework that helps us develop the Web layer more concisely, and it is naturally integrated with the Spring framework. Under Spring MVC, we generally divide projects into Service (logic layer) and Dao layer (database operations) , Entity layer (entity layer), Controller layer (control layer, return data to the front page)
  3. Core components:
    1. DispatcherServlet: The core CPU is responsible for receiving requests, dispatching them, and responding to clients.
    2. HandlerMapping: Processor mapper, according to the url to match to find the Handler that can be processed, and will encapsulate the requested interceptor and Handler together
    3. HandlerAdapter: Processor adapter, find the Handler according to HandlerMappering, adapt and execute the corresponding Handler
    4. Handler: request processor, the processor that handles the actual request
    5. ViewResolver: The view processor, according to the logical view/view returned by the Handler, parses and renders the real view, and passes it to the DispatcherServlet to respond to the client

11. What is the workflow of Spring MVC?

image.png

12. Tell me about SpringBoot?

       Spring Boot is developed based on Spring. The main feature is that 约定大于配置Spring Boot is used to quickly and agilely develop a new generation of applications based on the Spring framework, and it is closely integrated with the Spring framework to improve the Spring developer experience.

  1. Standalone Spring applications can be quickly created
  2. Containers such as Tomcat are embedded and can be run directly
  3. No need to use a bunch of cumbersome xml file configuration like Spring
  4. Automatically configure Spring through annotations and application.yaml configuration files
  5. It can quickly integrate common dependencies and provide pom simplified maven configuration

13. What is the automatic assembly principle of SpringBoot?

I feel that I can't understand it in a few words, so I should first sort it out according to the source code, and then use diagrams.

@SpringBootApplication // 标注这个类是一个SpringBoot的应用
public class Logback02Application {
    
    

    public static void main(String[] args) {
    
    
        // 将SpringBoot应用启动
        SpringApplication.run(Logback02Application.class, args);
    }
}

The place where the dream begins, the source code to be chased below is **@SpringBootApplication**the stuff in

image.png

This is how it looks after clicking in. The main thing to understand here is @SpringBootConfiguration, @EnableAutoConfiguration,@ComonentScan

13.1, @SpringBootConfiguration (SpringBoot configuration)

image.png

Click into @SpringBootConfiguration

image.png

Click into @Configuration

  1. @SpringBootConfiguration: SpringBoot configuration class
  2. @Configuration: spring configuration class
  3. @Component: is also a spring component

13.2, @EnableAutoConfiguration (automatic configuration)

image.png

点进@EnableAutoConfiguration

13.2.1, @AutoConfigurationPackage (automatic configuration package)

image.png

点进@AutoConfigurationPackage

@Import({AutoConfigurationPackages.Registrar.class}): Automatic configuration package registration

13.2.2, @Import({AutoConfigurationImportSelector.class}) (automatic import selection)

image.png

点进AutoConfigurationImportSelecto

There are a lot of things in it, let's talk about a few important ones

13.2.2.1, getAutoConfigurationEntry method

image.png
image.png

13.2.2.2、getCandidateConfigurations

    Click into getCandidateConfigurations, this is the method in getAutoConfigurationEntry

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    
    
    List<String> configurations = new ArrayList(SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()));
    ImportCandidates.load(AutoConfiguration.class, this.getBeanClassLoader()).forEach(configurations::add);
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories nor in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you are using a custom packaging, make sure that file is correct.");
    return configurations;
}

This is the getCandidateConfigurations method to get candidate configurations

image.png

Enter getSpringFactoriesLoaderFactoryClass

image.png

Enter EnableAutoConfiguration

Finally found that this is the main startup class

13.2.2.3、loadFactoryNames

image.png
      This loadFactoryNames is the method of getCandidateConfigurations to get all the loading configuration methods

13.2.2.4、META-INF/spring.factories

      This is also mentioned in getCandidateConfigurations. It is the core file of automatic configuration. Here is where to find it.

image.png

13.2.2.5、loadSpringFactories

image.png

private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
    
    
    Map<String, List<String>> result = (Map)cache.get(classLoader);
    if (result != null) {
    
    
        return result;
    } else {
    
    
        Map<String, List<String>> result = new HashMap();

        try {
    
    
            Enumeration<URL> urls = classLoader.getResources("META-INF/spring.factories");

            while(urls.hasMoreElements()) {
    
    
                URL url = (URL)urls.nextElement();
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                Iterator var6 = properties.entrySet().iterator();

                while(var6.hasNext()) {
    
    
                    Map.Entry<?, ?> entry = (Map.Entry)var6.next();
                    String factoryTypeName = ((String)entry.getKey()).trim();
                    String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                    String[] var10 = factoryImplementationNames;
                    int var11 = factoryImplementationNames.length;

                    for(int var12 = 0; var12 < var11; ++var12) {
    
    
                        String factoryImplementationName = var10[var12];
                        ((List)result.computeIfAbsent(factoryTypeName, (key) -> {
    
    
                            return new ArrayList();
                        })).add(factoryImplementationName.trim());
                    }
                }
            }

            result.replaceAll((factoryType, implementations) -> {
    
    
                return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
            });
            cache.put(classLoader, result);
            return result;
        } catch (IOException var14) {
    
    
            throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
        }
    }
}

Here you can load the META-INF/spring.factories file mentioned above

13.2.2.6、removeDuplicates和getExclusions

image.png
One of these two methods is to remove duplicate configurations, and the other is to process configurations that need to be excluded

13.3、@ComponentScan

      Scan beans annotated by @Component (@Service, @Controller). The annotation will scan all classes under the package where the startup class is located by default. You can customize not to scan some beans. As shown in the figure below, TypeExcludeFilter and AutoConfigurationExcludeFilter will be excluded from the container

13.4 General drawing

image.png

14. What is the principle of Spring Boot startup?

Spring Boot mainly does the following four things:

  1. Infer whether the type of application is a normal project or a web project
  2. Find and load all available initializers and set them in the initializers property
  3. Find all application listeners and set them to the listeners property
  4. Infer and set the definition class of the main method, and find the running main class

Guess you like

Origin blog.csdn.net/weixin_52487106/article/details/131130802