This article appears in the Interview Cheat Sheet series on Github at github.com/cosen1024/J… Domestic Gitee(downloadable PDF) : gitee.com/cosen1024/J…

1. What is dependency injection? How many ways can dependency injection be accomplished?

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

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

  • Constructor injection
  • Setter injection
  • Interface injection

In the Spring Framework, only constructors and setter injection are used.

2. Distinguish BeanFactory from ApplicationContext?

BeanFactory ApplicationContext
It uses lazy loading It uses instant loading
It makes the terminology explicitly provide resource objects It creates and manages resource objects itself
Internationalization is not supported Support internationalization
Dependency based annotations are not supported Support for dependency based annotations

BeanFactory and ApplicationContext

Advantages and disadvantages of BeanFactory:

  • Advantages: The application occupies few resources during startup. Therefore, the application that requires more resources has advantages.
  • Disadvantages: Running speed will be relatively slow. There is also the possibility of null-pointer exceptions, and the Bean life cycle created through the Bean factory is simpler.

Advantages and disadvantages of ApplicationContext:

  • Advantages: All beans are loaded at startup, and the system runs fast. Configuration problems can be found during system startup.
  • Disadvantages: the time-consuming operation is completed in the system boot, all objects can be preloaded, disadvantages is a large memory footprint.

3. What configuration methods does Spring provide?

  • Xml-based Configuration

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

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

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

<beans>
<context:annotation-config/>
<! -- bean definitions go here -->
</beans>
Copy the code
  • Java API-based configuration

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

  1. The @bean annotation plays with<bean />Characters with the same elements.
  2. The @Configuration class allows you to define inter-bean dependencies by simply calling other @Bean methods in the same class.

Such as:

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

4. 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: : In an HTTP session, one Bean definition corresponds to one instance. This scope is valid only in the case of web-based Spring ApplicationContext.
  • Global-session: 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

5. How to understand IoC and DI?

IOC is inversion of control, which in layman’s terms means that instead of creating instance objects ourselves, Spring’s bean factory creates and manages them for us. This is also the core idea of Spring, which is to implement dynamic dependencies on business components through an interface oriented programming approach. This means that IOC is Spring’s solution for application coupling. In practice, Spring specifies the Java classes (the full string of class names) to be instantiated through a configuration file (XML or Properties), including a set of initialized values for those Java classes, and reads the configuration file by loading. Using a spring-provided method (getBean()), we get the instance object we want to initialize according to the specified configuration.

  • Advantages: IOC or dependency injection reduces the amount of code in your application. It makes testing applications easy because singletons or JNDI lookups are no longer required in unit tests. Loose coupling is possible with a simple implementation and fewer intrusive mechanisms. The IOC container supports both frequent singletons and lazy load services.

DI: DI – Dependency Injection: The dependencies between components are determined at runtime by the container, which dynamically injects a Dependency into the component. The purpose of dependency injection is not to bring more functions to the software system, but to increase the frequency of component reuse and build a flexible and extensible platform for the system. Through the dependency injection mechanism, we can specify the resources needed by the target and complete our business logic through simple configuration without any code, regardless of where the specific resources come from and who implements them.

6. 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 to mark any class as a Spring Component. If a Bean does not know which layer it belongs to, it can be annotated using the @Component annotation. 8 @Repository: Corresponds to the persistence layer, namely Dao layer, which is mainly used for database related operations.
  • @service: corresponds to the Service layer, which involves complex logic and requires the Dao layer.
  • @Controller: corresponding to the Spring MVC control layer, the main user accepts the user request and calls the Service layer to return data to the front-end page.

7. Bean lifecycle in Spring?

The Bean life cycle is managed by the container. Mainly in the creation and destruction of the two phases.

Creation process:

1. Instantiate the bean object and set the bean properties; 2. The Bean’s container infrastructure-level dependencies are injected if the dependencies are declared through the Aware interface, which is Aware of some of its own properties. Container-managed beans generally do not need to know the state of the container and use the container directly. However, in some cases it is necessary to operate on the IOC container in the Bean. Container awareness needs to be set up in the bean. The SpringIOC container also provides this functionality, which is done through a specific Aware interface. The BeanNameAware interface, for example, knows its own name in the container. If this Bean already implements the BeanFactoryAware interface, you can use this method to get other beans. If the Bean implements the BeanNameAware interface, call the setBeanName() method, passing in the Bean name. If the Bean implements the BeanClassLoaderAware interface, call the setBeanClassLoader() method, passing in an instance of the ClassLoader object. If the Bean implements the BeanFactoryAware interface, call the setBeanFactory() method, passing in an instance of the BeanFactory object. 3, then will call BeanPostProcess postProcessBeforeInitialization front initialization method, main effect is in the Spring after complete instantiation, initialization, before the Spring container instantiation of Bean to add custom processing logic. Somewhat similar to AOP. 4. If you implement the afterPropertiesSet method of the BeanFactoryPostProcessor interface, do some custom things after the properties are set. 5. Call the init method defined by the Bean itself to do some initialization-related work. 6, calling BeanPostProcess rear initialization method, postProcessAfterInitialization after doing some bean initialization of custom work. 7. After the above creation, you can use the Bean in your application.

Destruction process:

When the Bean is no longer in use, it must disposable1, and when you implement the DisposableBean interface, the destroy method will be called. 2. If the destry-method attribute is configured, the configured destruction method will be called.

conclusion

Mainly grasp the creation process and destruction process of these two major aspects; Creation process: First, instantiate the Bean and set its properties. Set the dependency information according to the Aware interface implemented by the Bean (mainly BeanFactoryAware interface, BeanFactoryAware, ApplicationContextAware). The next call BeanPostProcess postProcessBeforeInitialization method, before completing the initial custom logic; The afterPropertiesSet method does some custom things after the properties are set; Call the init method defined by the Bean itself to do some initialization-related work; Then call postProcessAfterInitialization after doing some bean initialization of custom work. The invocation of these four methods is somewhat aOP-like. At this point, the Bean is initialized and ready to use. Destruction process: Call the destroy method, if you have implemented The DisposableBean, or if you have implemented a custom destruction method.

What is AOP?

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

9. What are the implementations of AOP?

The technologies for implementing AOP fall into two main categories:

  • Static proxy – refers to compilation using commands provided by the AOP framework so that AOP proxy classes can be generated at compile time, hence also called compile-time enhancement;
    • Compile-time weaving (special compiler implementation)
    • Class load-time weaving (special class loader implementation).
  • Dynamic proxy – Generates AOP dynamic proxy classes “temporarily” in memory at run time and is therefore also known as runtime enhancement.
    • JDKDynamic proxy: Receives proxied classes through reflection and requires that the proxied classes implement an interface. At the heart of JDK dynamic proxies are the InvocationHandler interface and Proxy class.
    • CGLIBDynamic proxy: If the target class does not implement the interface, thenSpring AOPWill choose to useCGLIBTo dynamically proxy the target class.CGLIB(Code Generation Library), is a Code Generation Library, can dynamically generate a class subclass at runtime, note,CGLIBIs dynamic proxying by inheritance, so if a class is marked asfinal, then it is unusableCGLIBDo dynamic proxy.

What is the difference between Spring AOP and AspectJ?

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

11. What if a bean with the same name appears in Spring?

  • The Bean with the same name in the same configuration file, whichever is defined at the top
  • If a Bean with the same name exists in different configuration files, the configuration file that is parsed later overwrites the one that was parsed first
  • A Bean with the same name appears in the file ComponentScan and @Bean. The same file as @bean is valid, @ComponentScan is not valid. Scanning in with @ComponentScan has the lowest priority because the Bean definitions it scans in are the first to be registered

12. How does Spring solve loop dependencies?

Spring’s handling of circular dependencies have three conditions: (1) the constructor of the circular dependencies: this dependence spring is processing, direct selling BeanCurrentlylnCreationException anomalies. ② Setter loop dependencies in singleton mode: loop dependencies are handled by “three-level caching”. ③ Non-singleton loop dependency: cannot be handled.

How to resolve setter loop dependencies in singleton mode

The initialization of Spring’s singleton is divided into three main steps:

CreateBeanInstance; createBeanInstance; createBeanInstance

(2) populateBean: fill the attribute. This step is mainly to fill the dependent attribute of multiple beans

(3) initializeBean: Call the init method in Spring XML.

As we can see from the singleton bean initialization steps described above, loop dependencies occur primarily in the first and second parts. That is, constructor loop dependencies and field loop dependencies.

Some field or setter of A depends on an instance object of B, and some field or setter of B depends on an instance object of A. After the first init (createBeanINstance) and the first singletonFactories (createBeanINstance), A tries to get(B) and finds that B is not yet created. So in the create process, when B initialize the first step, he realizes that he depends on object A, so he tries get(A), singletonObjects(definitely not, because A hasn’t fully initialized yet), earlySingletonObjects (also not), Try singletonFactories at level 3. Because ObjectFactory exposes itself, ObjectFactory. GetObject gets ObjectFactory (although A is not fully initialized, it’s better than nothing). B successfully completed the initialization stages 1, 2 and 3 after getting the object A, and put itself into the level-1 cache singletonObjects after complete initialization. At this point, A is returned to A, and the object that A can hold B has successfully completed its initialization phase 2 and 3. Finally, A has also completed its initialization and is included in the level 1 cache of singletonObjects. Fortunately, since B has obtained the object reference of A, the object that B now holds A has completed its initialization.

13. Do you know how SpringMVC works?

The principle is shown in the figure below:

Here’s a bit of a typo: Spring MVC’s entry function, the front-end controller DispatcherServlet, is used to receive requests and respond to results.

Process Description (Important) :

  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)

14. What design patterns are used in the Spring framework?

Factory Design pattern: Spring uses the factory pattern to create bean objects from the BeanFactory, ApplicationContext.

Proxy design pattern: Implementation of Spring AOP functionality.

Singleton design pattern: Beans in Spring are singleton by default.

Template method pattern: Spring’s jdbcTemplate, hibernateTemplate, and other classes that end in Template for database operations use the Template pattern.

Wrapper design pattern: Our project needs to connect to multiple databases, and different customers need to access different databases on each visit. This pattern allows us to dynamically switch between different data sources based on customer needs.

Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern.

Adapter pattern: The adapter pattern is used in Spring AOP enhancements or Advice, and is used in Spring MVC to adapt controllers.

15. What are the ways Spring transactions are implemented?

  • Programmatic transaction management: This means you can manage transactions programmatically, which provides a lot of flexibility but is difficult to maintain.
  • Declarative transaction management: This approach means you can separate transaction management from business code. You only need to manage transactions through annotations or XML configuration.

16. Propagation rules defined by Spring transactions

  • PROPAGATION_REQUIRED: Supports the current transaction, or creates a new one if there are none. This is the most common choice.
  • PROPAGATION_SUPPORTS: Supports the current transaction, and executes non-transactionally if there is no transaction currently.
  • PROPAGATION_MANDATORY: The current transaction is supported, and an exception is thrown if there is no transaction currently.
  • PROPAGATION_REQUIRES_NEW: Creates a transaction, and suspends the current one if it exists.
  • PROPAGATION_NOT_SUPPORTED: Executes an operation in a non-transactional manner, and suspends the current transaction, if one exists.
  • PROPAGATION_NEVER: Executes non-transactionally, throws an exception if a transaction currently exists.
  • PROPAGATION_NESTED: Executes within a nested transaction if a transaction currently exists. If there are no transactions currently, an operation similar to PROPAGATION_REQUIRED is performed.

17. Thread safety of singleton beans in Spring?

When multiple user requests a service at the same time, the container will assign each request a thread, when multiple threads can execute concurrently the request corresponding business logic (members), at this time will pay attention to, if the processing logic of singleton state changes (embodied in the member attribute of the singleton), thread synchronization must be considered. Thread-safety issues are caused by global and static variables. If there are only reads and no writes on a global variable or static variable per thread, the global variable is generally thread-safe. If you have multiple threads performing write operations at the same time, you generally need to consider thread synchronization, otherwise it may affect thread safety.

Stateless beans and stateful beans

  • Stateful is data storage. Stateful beans are objects that have instance variables, which can hold data and are non-thread-safe. No state is preserved between method calls.
  • Stateless is an operation that cannot save data. Stateless beans are objects that have no instance variables. Can’t hold data, is immutable, is thread-safe.

Stateless beans in Spring are best suited to the immutable, or singleton, pattern for sharing instances to improve performance. Stateful beans are unsafe in a multithreaded environment and are suitable for the Prototype pattern. Spring uses ThreadLocal to address thread-safety issues. If your Bean has multiple states (such as View Model objects), you’ll need to make your own thread-safe.

Here I also recommend a collection of computer books warehouse, the warehouse has hundreds of classic CS e-books, read the classic books will be deeper ~

Click this link to get you to the list of must-read books (PDF download included)

Github also has a repository at github.com/cosen1024/a… Welcome to star.