Java Development Interview--Spring Zone

Insert image description here

1. What are the core features and advantages of the Spring framework?

答:

  1. Lightweight and non-intrusive: Spring is a lightweight framework that does not forcefully change your application architecture, but uses dependency injection and oriented Features such as aspect programming provide a non-intrusive development method.
  2. Dependency Injection (Dependency Injection): Spring provides a powerful dependency injection function, which manages dependencies between objects through containers, reducing coupling and improving code reliability. Testability and maintainability.
  3. Aspect-Oriented Programming (Aspect-Oriented Programming): Spring supports aspect-oriented programming. Through AOP, cross-cutting concerns (such as logging, transaction management, etc.) can be separated from business logic It is extracted from the code to improve the modularity and reusability of the code.
  4. Container management: The core of Spring is the IoC container, which is responsible for creating, configuring and managing the life cycle of objects, simplifying the object creation and destruction process, and providing real-time management and expansion capabilities.
  5. Unified exception handling and transaction management: Spring provides a unified exception handling mechanism and flexible transaction management support, simplifying the complexity of developers handling exceptions and managing transactions.
  6. Integrate various open source frameworks and third-party libraries: Spring provides rich integration capabilities and can seamlessly integrate other open source frameworks and third-party libraries, such as database access, messaging Queues, caches, etc. provide developers with more choices and flexibility.
  7. Modularity and scalability: The Spring framework is composed of multiple modules, each module has specific functions. Developers can choose the modules they need based on project needs, and New function modules can be customized and expanded.
  8. Rich test support and documentation: The Spring framework provides good testing support and can easily perform unit testing and integration testing. In addition, the official provides detailed documentation and sample code to facilitate developers to learn and use.

2. What is your understanding of Dependency Injection and how does Spring implement dependency injection?

答:

DI understanding

Dependency injection is a design pattern that is used to decouple dependencies between components. In traditional programming models, components usually meet their functional requirements by directly creating and managing the objects on which they depend. However, doing so results in highly coupled code that makes components difficult to reuse, extend, and test. The purpose of dependency injection is to externalize the creation and management process of the objects on which components depend, thereby unbinding the direct binding of components to specific implementations and achieving low-coupling, easy-to-test, and scalable code.

The Spring framework is a widely used Java application development framework that provides powerful dependency injection capabilities. Springimplements dependency injection in the following ways:

  1. Constructor Injection (Constructor Injection): Inject dependent objects into components through the constructor. Declare dependent parameters in the constructor of the class and pass the dependent object through the constructor. The Spring container is responsible for parsing the constructor parameters, instantiating and injecting the corresponding dependent objects.
  2. Setter method injection (Setter Injection): Inject dependent objects into components through the setter method. Define the setter method in the component class and add corresponding annotations (such as @Autowired) to the properties that need to be injected with dependencies. After the Spring container instantiates the component, it injects the dependent object by calling the setter method.
  3. Interface Injection (Interface Injection): Inject dependent objects into components through interfaces. Components implement a specific interface that defines methods for injecting dependencies. The Spring container uses the dynamic proxy mechanism to generate a proxy object for the component after it is instantiated, and injects corresponding dependencies into the proxy object.
  4. Annotation Injection (Annotation Injection): Use annotations to directly mark dependencies on components. The Spring framework provides a series of annotations (such as @Autowired、@Resource, etc.) to achieve automatic injection of dependent objects by adding annotations to component fields, constructors or setter methods.

Spring's dependency injection function is implemented based on the IoC (Inverse of Control) container. The IoC container is responsible for managing the life cycle of components and dynamically injecting dependent objects based on the dependencies between components. In Spring, the commonly used IoC container is ApplicationContext. It is responsible for parsing and managing component dependencies, and implementing dependency injection based on configuration files or annotation configurations.

3. What are Inversion of Control and Aspect-Oriented Programming? How are these two concepts supported in Spring?

答:

Inversion of Control (IoC):

  1. Inversion of control is a design principle also known as dependency inversion. It refers to transferring the creation and management of dependencies between components to the container, thereby achieving highly decoupled code. In the traditional programming model, components usually meet their functional requirements by directly creating and managing the objects they depend on. Inversion of control externalizes this process and makes the container responsible for parsing and managing component dependencies.
  2. In Spring, inversion of control is implemented through the IoC container. The IoC container is responsible for creating and managing the life cycle of components, injecting dependency objects when needed, and transferring dependencies from the component itself to the container.
  3. In the Spring framework, the commonly used IoC container isApplicationContext. It can configure component dependencies through XML configuration files, Java annotations or Java code. The Spring container dynamically creates and manages component instances based on configuration information, and injects dependent objects into components, thus achieving inversion of control.

Aspect-Oriented Programming (AOP):

  1. Aspect-oriented programming is a programming paradigm used to solve problems with cross-cutting concerns. In traditional object-oriented programming, system functions are often scattered among various objects, resulting in duplicate and redundant code.
  2. AOP separates these cross-cutting concerns (such as logging, transaction management, etc.) from the main business logic, and encapsulates and processes them uniformly through aspects.
  3. In Spring, AOP functionality is provided by the Spring AOP module. Spring AOP implements aspect programming through dynamic proxy technology. It uses an interceptor to inject specific behavior before or after the target method is executed, or when an exception is thrown.
  4. When using AOP, you need to define a pointcut to specify the target method that needs to be intercepted, and then write an aspect class to encapsulate the logic of cross-cutting concerns. Spring AOP supports multiple types of advice (Advice), such as pre-advice (Before Advice), post-advice (After Advice), exception notification (AfterThrowing Advice), etc.
  5. Spring AOP can implement aspect definition and configuration through XML configuration files, Java annotations or Java code. No matter which method is used, Spring AOP will generate a proxy object for the target object at runtime and weave the aspect logic into the target method, thereby realizing aspect-oriented programming.

4. What are beans in the Spring framework, and how to define and manage beans?

答:

Bean is it

  • In the Spring framework, Beans refer to objects created, assembled and managed by the Spring container.
  • Beans represent various components or objects in the application, including services, data access objects, controllers, etc. By handing over objects to Spring container management, we can obtain powerful features such as dependency injection and AOP.

How to define Bean

  • Use the @Component annotation or its derived annotations (such as @Service, @Repository, @Controller) to mark the class to indicate that the class is a Bean. Spring will automatically scan and register classes marked by these annotations as beans.
  • Use the @Configuration annotation to mark a class, and then use the @Bean annotation to define a method. The return type is the type of the Bean. The Spring container calls these methods to create and register beans.
  • Use elements in the XML configuration file to explicitly define Bean configuration information.

How to manage beans:

  • Spring provides an IoC container (ApplicationContext) to manage the life cycle and dependencies of beans.
  • Bean instantiation: The Spring container is responsible for creating Bean instances based on the Bean definition. This can be done via constructors, factory methods, or other means.
  • Dependency injection: The Spring container is responsible for parsing the dependencies between beans and injecting dependent objects where needed. Dependency injection can be achieved through constructor injection, Setter method injection or field injection.
  • Life cycle management: Spring container manages the entire life cycle of beans, including initialization and destruction phases. Bean initialization and destruction operations can be defined by implementing the InitializingBean and DisposableBean interfaces, @PostConstruct and @PreDestroy annotations, and configuring init-method and destroy-method.
  • Scope: Spring supports multiple Bean scopes, such as Singleton, Prototype, Session, etc. You can define the scope of a Bean by setting the corresponding scope attribute in the @Bean annotation or specifying the scope in the XML configuration file.

5. What is your understanding and experience of using Spring MVC, and how to handle RESTful API requests?

答:

Spring MVC is a Java-based web application framework that provides a Model-View-Controller (MVC) architectural pattern to develop flexible and scalable web applications.

理解Spring MVC

  • Model-View-Controller (MVC): Spring MVC follows the MVC design pattern and divides the application into three main parts.
    • Model: Responsible for processing the data and business logic of the application.
    • View: Responsible for presenting data to users, usually through JSP, Thymeleaf or other template engines.
    • Controller: Receives and processes user requests, and decides how to update the model and select views.

Experience using Spring MVC:

  • Configuration: Set the basic configuration of Spring MVC through configuration files (such as XML or Java Config), such as URL mapping, view parser, interceptor, etc.
  • Annotations: Use annotations to simplify development. For example, use the @Controller annotation to mark the controller class, and the @RequestMapping annotation to specify the method for processing requests, etc.
  • Data binding: Spring MVC provides a data binding function, making it more convenient to directly bind request parameters in controller method parameters.
  • View parsing: By configuring the appropriate view parser, the logical view name returned by the controller is parsed into the actual view template, and then presented to the user.

Request RESTful API

  • Use @RequestMapping annotation: In Spring MVC, you can use @RequestMapping annotation to map RESTful API requests. Different processing methods can be defined by specifying the HTTP method (GET, POST, PUT, DELETE, etc.) and URL path.
  • Data binding and verification: Spring MVC supports automatically binding request parameters to the parameter object of the method. You can also use the @RequestBody annotation to bind the JSON or JSON in the request body. XML data is bound to objects. You can use JSR-303/349 validation annotations, such as @Validated and @Valid, to verify the validity of input parameters.
  • Return results: By using the @ResponseBody annotation, Spring MVC allows controller methods to directly return data objects and automatically serialize responses into JSON or other formats.
  • Exception handling: You can use the @ControllerAdvice annotation to define a global exception handling class, capture and handle RESTful API exceptions, and return appropriate error responses.

6. What is the difference between Spring Boot and Spring? What are the features and advantages of Spring Boot?

答:

Spring Boot is an extension of the Spring framework, mainly used to simplify and accelerate the development of Spring-based applications.

District

  • Configuration: In traditional Spring, a large amount of configuration is required manually, including XML configuration files, annotation configuration, etc. Spring Boot adopts the principle of convention over configuration, reducing the configuration workload and simplifying development through automatic configuration and default configuration.
  • Dependency Management: In traditional Spring development, it is necessary to manually manage the version compatibility of various dependent libraries. Spring Boot introduces "Starter" dependencies, which simplifies dependency management. You can select the Starter dependencies of relevant functional modules as needed, and automatically parse and import related dependency libraries during compilation.
  • Production-ready features: Spring Boot provides some features required for production environments, such as health checks, performance indicator monitoring, fault handling, etc. These features help quickly build reliable and efficient applications.

Characteristics 和优势

  • Simplified configuration: Spring Boot reduces tedious configuration work through automatic configuration and default configuration, so developers can focus more on the implementation of business logic.
  • Embedded server: Spring Boot has built-in common web servers such as Tomcat and Jetty, allowing applications to run directly as executable JAR packages without the need for external containers.
  • Automated dependency management: Spring Boot's "Starter" dependency simplifies dependency management. Just add the Starter dependency of the relevant functional module to automatically import the required dependency library. .
  • Microservice support: Spring Boot provides good support for microservice architecture, including service registration and discovery, configuration center, load balancing, etc.
  • Monitoring and Management: Spring Boot integrates various monitoring and management tools, such as Actuator, which can view application performance indicators, health status, etc. in real time.
  • Externalized configuration: Spring Boot supports externalizing the configuration information of the application, which can be configured through property files, environment variables, command line parameters, etc.

7. How to use Spring for transaction management? Explain Spring's transaction propagation behavior and isolation levels.

答:

In Spring, you can usedeclarative transactionsmanagement orprogrammatic transactions Management to handle transactions.

Steps to use Spring for transaction management:

  • Configure data source: First you need to configure the data source, such as database connection pool.
  • Configure transaction manager: Configure the transaction manager, for example, use the specific implementation class of the PlatformTransactionManager interface provided by Spring, such as DataSourceTransactionManager.
  • Declare transactions: Add the @Transactional annotation to the method that requires transaction management, indicating that the method requires transaction management.
  • Specify transaction attributes: You can specify the propagation behavior and isolation level of the transaction through the attributes annotated with @Transactional.

Transaction Propagation:

  • REQUIRED (default value): If the transaction currently exists, join the transaction; if the transaction does not exist, create a new transaction.
  • REQUIRES_NEW: Create a new transaction each time the method is called, pausing the current transaction (if it exists).
  • SUPPORTS: If a transaction currently exists, join the transaction; if there is no transaction, execute in a non-transactional manner.
  • MANDATORY: If a transaction currently exists, join the transaction; if there is no transaction, throw an exception.
  • NOT_SUPPORTED: Perform the operation in a non-transactional manner, suspending the transaction if it currently exists.
  • NEVER: Perform the operation in a non-transactional manner and throw an exception if a transaction currently exists.
  • NESTED: If a transaction currently exists, a nested transaction is created and executed in an independent savepoint; if there is no transaction, the behavior is similar to REQUIRED.

Transaction Isolation Level:

  • DEFAULT (default value): Use the database default transaction isolation level.
  • READ_UNCOMMITTED: The lowest isolation level, allowing reading of uncommitted data.
  • READ_COMMITTED: Allows reading of committed data and prevents dirty reads.
  • REPEATABLE_READ: Ensure that the same query returns the same results, preventing dirty reads and non-repeatable reads.
  • SERIALIZABLE: The highest isolation level, ensuring serial execution of transactions and preventing dirty reads, non-repeatable reads and phantom reads.

In Spring, transaction management is implemented through AOP (Aspect-Oriented Programming). Spring manages the start, commit, rollback and other operations of transactions by applying transaction enhancers before and after method calls.

It should be noted that the configuration and use of transaction management may vary depending on the specific Spring version and the persistence technology used (such as Hibernate, JPA, etc.). Please adjust according to the specific situation.

8. How do you perform unit testing and integration testing, and how does using Spring simplify the testing process?

答:

单原测试

  • Unit testing is testing of the smallest testable unit in an application (usually a class or method).
  • In unit testing, unit testing frameworks such as JUnit are usually used to write and run test cases to verify the logical correctness of each unit.
  • Spring cansimplify the unit testing process, mainly as follows:
    • Use Mock objects: Spring provides simulation frameworks such as Mockito to simulate the behavior of dependent objects, making unit testing more independent and controllable.
    • Inject dependencies: Spring's dependency injection mechanism can easily inject the dependent objects of the unit under test, making the test more concise and readable.
    • Use test environment configuration: Spring provides the @ContextConfiguration annotation, which can load specific configuration files or configuration classes in the test environment to create an ApplicationContext container and manage dependent objects. life cycle.

Collection Examination

  • Integration testing is the testing of interactions between multiple components or modules to verify that they work together correctly.
  • In integration testing, it is necessary to simulate the real environment and data and comprehensively test each component of the system.
  • Spring cansimplify the process of integration testing, mainly as follows:
    • Use an in-memory database: Spring provides an in-memory database (such as H2, HSQLDB, etc.), which can replace the real database during testing to avoid dependence on and damage to real data.
    • Configure transaction manager: Spring's transaction manager can easily configure and manage transactions, and simulate the start, commit and rollback of transactions in the test environment.
    • Test framework support: Spring is closely integrated with test frameworks such as JUnit and provides various test annotations and tool classes, such as @SpringBootTest annotations, TestRestTemplate, etc., which simplifies integration testing Written and executed.

In the above way, Spring simplifies the testing process, making unit testing and integration testing easier and more efficient. It provides dependency injection, Mock objects, test environment configuration, in-memory database, transaction manager and other functions to help developers write reliable test cases and verify the correctness and stability of applications. These features make test writing and execution more convenient, while improving test readability and maintainability.

9. How to use Spring Cloud to register, discover and call services in a distributed system?

答:

In distributed systems, Spring Cloud provides a complete solution to realize service registration, discovery and invocation.

Service registration and discovery:

  • Using Eureka: Spring Cloud provides Netflix Eureka as the default service registration and discovery component. By introducing the corresponding dependencies in the application and configuring the Eureka server address, the application can register itself on the Eureka server. (Now mainstream Nacos)
  • Use Consul or ZooKeeper: In addition to Eureka, Spring Cloud also supports the use of other registration centers such as Consul or ZooKeeper. Through the corresponding dependencies and configurations, applications can register themselves on these registration centers.

Service call:

  • Using Ribbon: Spring Cloud's Ribbon is a load balancing client that can be integrated with the service registry. By introducing Ribbon dependency into the application, the @LoadBalanced annotation can be used to implement load-balanced service calls where other services need to be called.
  • Using Feign: Spring Cloud's Feign is a declarative web service client that simplifies HTTP calls between services. By introducing Feign dependency into the application and using the @FeignClient annotation to declare the calling interface to the target service, Spring Cloud will generate a specific proxy class at runtime to handle service calls.

Service fault tolerance and circuit breaker:

  • Using Hystrix: Spring Cloud's Hystrix is ​​a fault-tolerant and circuit breaker framework for handling failures and delays in distributed systems. By introducing Hystrix dependency into the application and combining it with the @HystrixCommand annotation, fault tolerance and circuit breaker for service calls can be achieved.

Placement center :

  • Use Config Server: Spring Cloud's Config Server allows centralized management of application configurations and provides the ability to dynamically refresh configurations. By introducing the Config Server dependency into the application and configuring the Config Server address, centralized management and dynamic refresh of the configuration can be achieved.

Through the above steps, service registration, discovery and invocation can be easily achieved using Spring Cloud. It provides a variety of registration center choices, such as Eureka, Consul and ZooKeeper, and integrates functions such as load balancing, declarative service invocation, fault-tolerant circuit breaker and configuration center, making the development and operation and maintenance of distributed systems simpler and more reliable. .

10. Which modules and functions of Spring do you use in actual projects, and what challenges and solutions do you encounter?

答:

Examples of common modules and functions using Spring as well as possible challenges and solutions:

  1. Spring MVC
    • Web application development and deployment using Spring MVC.
    • Possible challenges: how to handle a large number of requests and responses, how to manage the life cycle of controllers and views, how to optimize performance, etc.
    • Solution: Use Spring's asynchronous request processing, interceptors, filters, caching and other features to optimize performance, and use appropriate design patterns and architecture to manage the life cycle of controllers and views.
  2. Spring Data
    • Use Spring Data to simplify operations on the data access layer and support various databases and ORM frameworks.
    • Possible challenges: how to handle complex queries and relationships, how to optimize performance, how to handle transactions, etc.
    • Solution: Use Spring Data's query DSL, dynamic query, relational query, transaction management and other features to solve the problem, and use appropriate indexes and caches to optimize performance.
  3. Spring Security
    • Use Spring Security to enhance security, including authentication, authorization, encryption, etc.
    • Possible challenges: how to handle different authentication and authorization methods, how to protect sensitive data and resources, how to handle session management, etc.
    • Solution: Use Spring Security's various authentication and authorization mechanisms, encryption algorithms, session management and other features to solve the problem, and follow best practices to protect sensitive data and resources.
  4. Spring Boot
    • Use Spring Boot to quickly build and deploy applications, providing functions such as automatic configuration and dependency management.
    • Possible challenges: how to manage the life cycle of the application, how to handle configuration and dependency conflicts, etc.
    • Solution: Use Spring Boot’s launcher, automatic configuration, command line tools and other features to simplify and optimize the development process, and use appropriate design patterns and architecture to manage the application life cycle.

11. What design patterns does Spring use? Where exactly are these design patterns used?

答:

  1. Dependency Injection (Dependency Injection):
    • Spring uses the dependency injection pattern to manage dependencies between objects. By separating object dependencies from code, Spring can manage and configure these objects in a more loosely coupled manner.
  2. Factory Pattern (Factory Pattern):
    • Spring uses the factory pattern to create and manage bean instances. For example, Spring's ApplicationContext acts as a BeanFactory and can create bean instances based on configuration files or annotations.
  3. Singleton Pattern (Singleton Pattern):
    • Beans in Spring are in singleton mode by default, that is, only one bean instance will exist in the container. This saves resources and ensures the same instance is used throughout the application.
  4. Proxy Pattern (Proxy Pattern):
    • Spring AOP (Aspect-Oriented Programming) uses the proxy pattern to implement the functionality of cross-cutting concerns. Through dynamic proxy, additional logic is inserted before and after the method execution of the target object, such as logging, transaction management, etc.
  5. Observer Pattern (Observer Pattern):
    • Spring's event mechanism is based on the observer pattern. By defining events, listeners, and publishers, you can decouple objects and notify relevant listeners when specific events occur.
  6. Template Pattern (Template Pattern):
    • Spring's template classes such as JdbcTemplate and HibernateTemplate use the template pattern to provide a consistent data access interface and handle common database operations, such as opening connections, executing queries, etc.
  7. Adapter Pattern (Adapter Pattern):
    • Spring's MVC framework uses the adapter pattern to handle different types of requests. Adapters allow you to convert specific types of requests into a form that a controller can handle.
  8. Strategy Pattern (Strategy Pattern):
    • Spring's Validator interface uses the strategy pattern to implement different validation rules. By defining different verification strategies, the appropriate strategy can be selected for verification at runtime.

12. How to avoid importing some functions in the configuration in spring?

答:

In Spring, you can use conditional annotations or conditional configuration to achieve some functions without importing the configuration.

Conditional annotation:

  • You can use@Conditional annotations to control the instantiation of beans and the import of configurations based on specific conditions.
  • For example, we can define a custom condition class to check whether a specific bean or environment variable currently exists. If it exists, the corresponding configuration will be imported; otherwise, it will not be imported.

Commonly used conditional annotations:

  1. @ConditionalOnProperty: The configuration will only be loaded when the specified attribute exists and has the specified value. Conditions can be specified by setting attributes such as value and havingValue.
  2. @ConditionalOnClass: The configuration will only be loaded when the specified class exists in the classpath. The class name can be specified by setting the value attribute.
  3. @ConditionalOnBean: The configuration will be loaded only when the specified Bean exists in the container. You can specify the type of Bean by setting the value attribute.
  4. @ConditionalOnMissingBean: The configuration will be loaded only when the specified bean does not exist in the container. You can specify the type of Bean by setting the value attribute.
  5. @ConditionalOnExpression: Determine whether to load the configuration based on the result of the SpEL expression. SpEL expressions can be specified by setting the value attribute.

Conditional configuration:

  • Use@Profile or @Import annotations to control bean instantiation and configuration import based on specific configuration files or environment variables.
  • For example, we can define a configuration file with profile "test", define the corresponding beans in the configuration file, and then reference them in the main configuration file through the @Profile annotation. In this way, in the "test" environment, the relevant configuration of the configuration file will be automatically imported; in other environments, it will not be imported.

13. Tell me what annotations are in SpringBootApplication?

答:

In the main class of a Spring Boot application, the @SpringBootApplication annotation is usually used to identify the class as the entry point of a Spring Boot application.

@SpringBootApplicationThe annotation itself is a combined annotation, which contains a series of commonly used annotations, including:

  1. @Configuration: Indicates that this class is a configuration class used to define and configure Beans.
  2. @EnableAutoConfiguration: Enable Spring Boot's automatic configuration mechanism to automatically configure the behavior of Spring applications based on project dependencies and configurations.
  3. @ComponentScan: Specifies the base package path for scanning components to discover and register Spring-managed beans.

Based on the functions of the above three annotations,@SpringBootApplication annotations can combine configuration, automatic configuration and component scanning, making it easier for developers to build and configure Spring Boot applications.

14. Tell us about the circular dependencies in spring?

答:

In the Spring framework, circular dependency refers to the mutual dependence between two or more beans, forming a circular reference relationship.

In this case, when the Spring container tries to create these beans, it may cause infinite recursive calls, causing stack overflow or failure to create beans normally.

When two beans depend on each other, Spring'sdefault creation process is as follows:

  1. First, create an instance of Bean A.
  2. In the process of creating Bean A, it is found that Bean B needs to be depended on.
  3. Since Bean B has not been created yet, Spring will try to create an instance of Bean B first.
  4. In the process of creating Bean B, it is found that it needs to depend on Bean A.
  5. Since Bean A has not been created yet, Spring will try to create an instance of Bean A again.
  6. Then it goes back to step 2, forming a circular dependency, resulting in infinite recursive calls.

In order to solve the problem of circular dependencies, Spring provides a default strategy and third-level cache.

Clearance strategy

  • Spring uses the singleton mode to manage Beans by default, that is, by default, each Bean will only be created once. When circular dependencies occur, the default strategy is to put beans that have not yet been fully created into the "early reference" cache to solve the problem of circular dependencies.
  • When creating a bean, if it is found that it needs to depend on another bean that has not yet been created, Spring will return the bean instance in the early reference cache instead of continuing to create it recursively.

Level 3 cache:

  • In order to better solve the problem of circular dependencies, Spring also introduced a three-level cache mechanism. When a bean is created, Spring will put it into three levels of cache, namely singletonFactories, earlySingletonObjects and singletonObjects.
  • Through these three caches, Spring can solve the circular dependency problem when creating beans and ensure that each bean is only created once.

15. How to solve circular dependencies in spring?

答:

In the Spring framework, circular dependency refers to the situation where two or more beans depend on each other, forming a circular reference. Spring provides several methods to solve circular dependency problems:

  1. Constructor injection: Inject dependencies as parameters through the constructor instead of using autowiring annotations (such as @Autowired) for property injection. This approach avoids circular dependency problems because the constructor is only executed once when the object is created, while property injection may occur after the object is created. (Use @Autowired annotation with @Lazy annotation to solve the problem)
  2. Setter method injection: Use the Setter method in the Bean to inject dependencies and set lazy loading of dependencies. Lazy loading can ensure that the bean is fully initialized before being injected, thereby solving the problem of circular dependencies. (Use @Autowired annotation with setter method to solve)
  3. Use @Lazy annotation: When declaring a Bean, use the @Lazy annotation to delay the initialization of loading the Bean. This avoids circular dependency problems because beans are initialized only when needed.
  4. Use proxy objects: When there are circular dependencies, they can be solved by using proxy objects. Spring provides two proxy methods: JDK dynamic proxy and CGLIB proxy. By adding the @Scope("prototype") annotation to the relevant bean to make it a prototype-scoped bean, proxy objects are used to resolve circular dependencies. (Or create a proxy object exposed in advance and then inject it into the circularly dependent Bean)

16. Which places in spring are implemented using the reflection mechanism?

答:

  1. Bean instantiation: Spring instantiates Bean through reflection mechanism. When the Spring container starts, it will scan all classes annotated with @Bean, @Controller, @Service, @Repository and other annotations in the configuration file, and use the reflection mechanism to create instances of these Beans.
  2. Property injection: Spring implements automatic assembly through the reflection mechanism, that is, automatically injects dependencies between beans into beans. When calling the Bean's constructor or setter method, Spring injects property values ​​through the reflection mechanism.
  3. AOP proxy: Spring implements AOP functions through the reflection mechanism. When an aspect is defined using the @Aspect annotation, Spring will use the reflection mechanism to create a proxy object, weave the aspect into the target object, and execute the enhancement logic.
  4. Event monitoring: Spring implements event monitoring function through reflection mechanism. When an event occurs, Spring will call all relevant methods that have registered listeners interested in the event through the reflection mechanism.
  5. Database access: In Spring, when using JdbcTemplate to implement database access, Spring will call the setter method of JavaBean through the reflection mechanism to map the query results to the properties of JavaBean.

17. Tell me about the implementation principle of the three-layer caching mechanism in spring?

答:

In the Spring framework, the bean creation process is a relatively complex process involving multiple stages and multiple caches. Among them, the three-layer caching mechanism is one of the key mechanisms used by the Spring framework to improve the efficiency of bean creation.

Spring framework'sthree-layer caching mechanismincludes the following three layers:

  1. singletonObjects cache: This cache is used to store fully initialized, singleton mode Bean instance objects. If you want to obtain a singleton object, first check whether the target object exists in the cache, and return it directly if it exists.
  2. earlySingletonObjects cache: This cache is used to store singleton Bean instance objects that are exposed in advance but have not yet been fully initialized. During the bean creation process, when a Bean instance is created, Spring will store the Bean instance in the earlySingletonObjects cache for use when handling circular dependencies.
  3. singletonFactories cache: This cache is used to store the ObjectFactory used to create singleton beans. During the bean creation process, when a Bean instance is created, Spring will store the ObjectFactory corresponding to the Bean instance in the singletonFactories cache for use when handling circular dependencies.

The implementation principle of the three-layer caching mechanism is as follows:

  1. When obtaining a singleton Bean instance, it will first check whether the target object exists in the singletonObjects cache, and return it directly if it exists. If it does not exist, the Bean creation process will be entered.
  2. When creating a Bean instance, it will first check whether the target ObjectFactory exists in the singletonFactories cache. If it exists, use the ObjectFactory to create a Bean instance. If the target ObjectFactory does not exist in the cache, the createBean method will be called to create a Bean instance, and the ObjectFactory corresponding to the Bean instance will be stored in the singletonFactories cache.
  3. After creating the Bean instance, Spring will store the Bean instance in the earlySingletonObjects cache and complete other initialization operations. If a circular dependency is found during the creation of a Bean instance, Spring will obtain the corresponding Bean instance from the earlySingletonObjects cache and return it. If the target Bean instance does not exist in the earlySingletonObjects cache, you need to enter the Bean creation process again.
  4. Finally, Spring will store the fully initialized, singleton mode Bean instance in the singletonObjects cache for use the next time the Bean instance is obtained.

18. Tell me what annotations are in spring and their functions?

答:

  1. @Component: Used to identify a class as a component that can be scanned, recognized and managed by the Spring container.
  2. @Controller: Used to identify a class as a controller, usually used to handle HTTP requests and return responses.
  3. @Service: Used to identify classes as service layer components, usually used to encapsulate business logic.
  4. @Repository: Used to identify a class as a data access layer component, usually used to interact with a database or other persistence mechanism.
  5. @Autowired: Used for automatic assembly of dependencies, and can be used for constructors, member variables, setter methods and any other methods.
  6. @Qualifier: Used with @Autowired to specify the specific dependency injection bean name.
  7. @Value: Used to inject attribute values ​​into Beans, and supports obtaining them from configuration files, environment variables and other sources.
  8. @RequestMapping: Used to map the HTTP request path to the controller's processing method.
  9. @ResponseBody: Used to return the method return value directly to the client as the content of the HTTP response.
  10. @PathVariable: Used to obtain parameter values ​​in the URL path.
  11. @RequestParam: Used to get the value of request parameters.
  12. @Configuration: Used to identify a class as a configuration class, usually used with @Bean to define the creation and configuration of Bean.
  13. @Bean: Used to register the object returned by the method as a Bean and manage it by the Spring container.
  14. @Aspect: Used to define aspects, usually used together with other annotations to implement AOP functions.
  15. @Transactional: Used to identify transaction processing methods and incorporate operations within the method body into transaction management.

19. In springboot, how do you want to run a custom bean class or some functions when they are started?

答:

In Spring Boot, you can execute custom logic when the application starts by implementing the CommandLineRunner interface or using the @PostConstruct annotation.

RealCommandLineRunnerEntrance:

  • Create a class and implement the CommandLineRunner interface, then override the run method and write the logic that needs to be executed when the application starts.
  • By marking the class as @Component, Spring will automatically scan and instantiate it as a Bean and call the run method when the application starts.

Use@PostConstructComment:

  • Add@PostConstruct annotation to the method that needs to be executed when the application starts. This method will be executed immediately after the Bean is initialized and dependency injection is completed.
  • By marking the class as @Component, Spring will instantiate it as a Bean and call the init method after the initialization is complete.

20. What is the difference between context (ApplicationContext) and bean factory (BeanFactory) in spring?

答:

In the Spring framework, ApplicationContext and BeanFactory are the two core container interfaces. The differences between them are as follows:

  1. defined义:
    • ApplicationContext: It is a sub-interface of BeanFactory and provides more functions, including internationalization support, event publishing, resource loading, etc.
    • BeanFactory: It is Spring's basic container interface, providing basic dependency injection and Bean management functions.
  2. Supernatural ability:
    • ApplicationContext: In addition to providing the functions of BeanFactory, it also provides more advanced functions, such as automatic assembly, AOP, declarative transactions, message processing, etc.
    • BeanFactory: Provides basic dependency injection and Bean management functions, and is the most basic container of Spring.
  3. 预加载
    • ApplicationContext: All singleton beans will be pre-instantiated when the container starts.
    • BeanFactory: Beans are only instantiated when used.
  4. Resource management:
    • ApplicationContext: supports international resource management, event publishing and monitoring, automatic assembly, etc.
    • BeanFactory: Mainly focuses on the creation and management of Beans and does not provide other advanced functions.
  5. Extensibility:
    • ApplicationContext: supports various extension points and can customize the implementation, such as extending the functions of the Spring container by customizing BeanPostProcessor, BeanFactoryPostProcessor, etc.
    • BeanFactory: Provides basic extension points, but is more limited than ApplicationContext.

21. In what scenarios will the @Transactional annotation become invalid in spring?

答:

In Spring, @Transactional annotation is used to declare the boundaries of transactions, and it can be applied at the class level and method level.

In some scenarios,@Transactional annotation may become invalid. The specific situation is as follows:

  1. Exception not caught: If an uncaught exception is thrown in a transaction method, and the exception is not a default exception that can be rolled back by Spring's transaction manager ( Such as RuntimeException and its subclasses), then the transaction will not be rolled back. If you want the transaction to be rolled back, you need to ensure that the exception is caught or is an exception that the Spring transaction manager can roll back.
  2. Non-public methods: If other non-public methods (that is, non-proxied methods) are called inside the class, then using the @Transactional annotation will also cause the transaction to fail. This is because Spring's transaction management is based on AOP's dynamic proxy implementation. Only methods called through the proxy object can be intercepted and applied by the transaction manager.
  3. Self-calling: If one method calls another method in the same class, and both methods are modified by the @Transactional annotation, the transaction annotation will be invalid. . This is because Spring's transaction annotations are implemented through AOP aspects. Only methods called from the outside can be intercepted by the proxy. Method calls within the same class will not trigger the proxy.
  4. Asynchronous method: If Spring's asynchronous method (@Async annotation) is used, and the @Transactional annotation is used in the asynchronous method, the transaction will also be invalid. This is because the asynchronous method will be executed in a new thread and cannot guarantee the same transaction context as the current thread.
  5. Method calls between different classes: If a method modified by the @Transactional annotation is called in a method of another class (that is, a cross-class call), and is The called method is also modified with @Transactional annotation, then the transaction annotation will be invalid. This is because transaction annotations only work on proxy objects and do not propagate transactions in calls between classes.

22. What are the affairs of spring?

答:

Spring provides the followingcommon transaction management methods:

  1. Programmatic transaction management:
    • UseTransactionTemplate orPlatformTransactionManager for programmatic transaction management. Control transactions by manually opening, committing, or rolling back transactions in code.
  2. Declarative transaction management:
    • Annotation-based: Use@Transactional annotations to declare transaction behavior on methods or classes.
    • Based on XML configuration: By defining transaction attributes in the XML configuration file, such as tx:advice and tx:attributes, Implement declarative transaction management.
  3. Annotation-driven Transaction Management (Annotation-driven Transaction Management):
    • Use@EnableTransactionManagement annotation to enable annotation-driven transaction management.
    • Use@Transactional annotations on methods or classes to declare transaction behavior.
  4. XML configuration based on AspectJ:
    • Use tx:advice and aop:config tags combined with AspectJ expressions to define transaction aspects in the XML configuration file and specify transaction attributes.
  5. Combined configuration based on annotations and AspectJ:
    • Use@EnableTransactionManagement annotation to enable annotation-driven transaction management.
    • Define the transaction aspect in the XML configuration file and specify the transaction attributes.

23. What is the life cycle of the SpringBean container?

答:

The life cycle of the Spring container can be divided into the following stages:

  1. Instantiation:
    • When the application starts, the Spring container reads the configuration file or annotations and instantiates the beans based on the configuration information. This can be done through constructors, static factory methods, or factory beans.
  2. Populate Properties:
    • After instantiating a bean, the Spring container assigns the property values ​​specified in the configuration file or annotations to the corresponding properties of the bean. This can be done through Setter methods or direct access to member variables.
  3. Initialization:
    • After the property is assigned, the Spring container will call the Bean's initialization method (if defined), such as the method annotated with the @PostConstruct annotation or the afterPropertiesSet() method that implements the InitializingBean interface. Developers can perform some initialization operations at this stage.
  4. 使用(In Use)
    • After initialization is completed, the bean is in a usable state and can be used by other beans or components.
  5. 销毁(Destruction)
    • When the application is closed or the Spring container is destroyed, the Spring container will call the Bean's destruction method (if defined). Resource release and cleanup operations can be performed through the methods marked with @PreDestroy annotations or the methods that implement the DisposableBean interface. destroy()

It should be noted that the bean life cycle can be affected by the Spring container. For example, a bean with singleton scope will be created when the container is started and destroyed when the container is destroyed; a bean with prototype scope will create a new instance every time it is retrieved, and the application will be responsible for destroying it.

In addition, you can intercept the initialization process of the Bean and customize it by implementing the BeanPostProcessor interface. The BeanPostProcessor interface provides the beforeInitialization() and afterInitialization() methods, allowing developers to perform some additional processing before and after Bean initialization.

24. What is spring assembly?

答:

Spring Assembly refers to combining individual components (Beans) through configuration or annotation to form a complete application.

In Spring, there arethree common assembly methods:

  1. XML placement:
    • Define beans through elements in XML configuration files, and use elements to set property values ​​and dependencies of the beans. Multiple profiles are then combined together via elements. This method is already a relatively traditional method and was widely used in early versions of Spring.
  2. Annotation placement:
    • Use annotations to mark beans, and implement bean assembly through annotations. For example, use @Component, @Service, @Repository and other annotations to define beans, and use @Autowired or @Resource annotations to inject dependencies.
  3. Java deployment:
    • Use Java classes instead of XML configuration files to configure and assemble Beans through specific annotations (such as @Configuration, @Bean) and Java code. This approach is more flexible and type-safe, and can take full advantage of the features of the Java programming language.

The purpose of Spring assembly is to connect various components together to form a loosely coupled application. Through assembly, dependency injection (Dependency Injection) can be implemented, and the dependencies between components are managed by the Spring container, instead of manually creating and maintaining the relationships between objects. This improves code maintainability, testability, and supports interface-oriented programming. At the same time, assembly can also help achieve horizontal expansion and modular development, making applications more flexible and scalable.

25. What are the methods of automatic assembly in spring?

答:

In Spring, autowiring is a dependency injection (Dependency Injection) method that can automatically establish dependencies between beans. Spring provides a variety of automatic assembly methods, including:

  1. byName automatic arrangement:
    • Dependencies are automatically wired based on the name of the bean. That is, if the property name of a Bean is the same as the name of other Bean, Spring will automatically inject the property into the corresponding Bean instance. This method requires that the name of the Bean must be exactly the same as the property name, and the Bean must have been defined in the container.
  2. byType automatic arrangement:
    • Automatically wire dependencies based on bean type. That is, if the property type of a Bean is the same as the type of other Bean, Spring will automatically inject the property into the corresponding Bean instance. This method requires that the bean type must be unique, and the bean must have been defined in the container.
  3. constructor automatic arrangement:
    • Automatically wire dependencies based on constructor parameter types. That is, Spring will automatically find Bean instances in the container that match the constructor parameter types and inject them into the constructor. This method requires that the bean must have a constructor, and the parameter type of the constructor must match the bean type defined in the container.
  4. autowire-candidate属性
    • You can control whether to participate in automatic assembly by setting the autowire-candidate attribute of the Bean. If this property is set to false, the bean will not be autowired.

It should be noted that when using automatic assembly, you should try to avoid ambiguous dependencies, otherwise it may lead to the inability to determine which Bean instance is assembled. At the same time, since automatic wiring will hide the dependencies between beans, special attention is also required during maintenance and debugging.

盈若安好,便是晴天

Guess you like

Origin blog.csdn.net/qq_51601665/article/details/134237587