Java Road to God: Java Interview Preparation (13)

Three, Spring framework

1. What is Spring

Spring is a lightweight Java development framework, originally created by Rod Johnson, with the purpose of solving the coupling problem of business logic and other layers of enterprise-level application development and simplifying development

2. What are the benefits of using the Spring framework

3. What is the design goal, design philosophy, and core of the Spring framework?

**Spring design goals: **Spring provides developers with a one-stop lightweight application development platform

Spring design philosophy: In the development of JavaEE, it supports POJO and JavaBean development methods, makes applications interface-oriented development, and fully supports OO (object-oriented) design methods; Spring implements the management of object coupling relationships through the IoC container and realizes dependency inversion, The dependencies between objects are handed over to the IoC container to achieve decoupling;

The core of the Spring framework: IOC container and AOP module. Manage pojo objects and their coupling relationships through the IOC container; enhance services in a dynamic proxy manner through AOP

IOC keeps the cooperating components loosely coupled, while AOP programming allows you to separate the functions that are spread across all layers of the application to form reusable functional components

4. Spring advantages and disadvantages

advantage:

  • Facilitate decoupling and simplify development. Spring is a large factory that can delegate the creation of all objects and the maintenance of dependencies to Spring for management
  • AOP programming support. Spring provides aspect-oriented programming, which can conveniently implement functions such as program's interception of permissions, operation monitoring, etc.
  • Support for declarative transactions. Only need to configure to complete the management of things, without manual programming
  • Convenient for program testing, Spring supports Junit4, you can easily test Spring programs through annotations
  • Convenient integration of various excellent frameworks, Spring does not exclude various excellent open source frameworks, and provides direct support for various excellent frameworks internally
  • Reduce the difficulty of using JavaEE API

Disadvantages:

  • Spring relies on reflection, reflection affects performance
  • High barriers to use
  • More configuration

5. What design patterns are used in the Spring framework

1. Factory mode: BeanFactory is the embodiment of simple factory mode, used to create instances of objects

2. Singleton mode: Bean defaults to singleton mode

3. Proxy mode: SpringAop function uses JDK dynamic proxy and CGLIB bytecode generation technology

4. Template method mode: used to solve the problem of code duplication, such as RestTemplate, JmsTemplate

5. Observer mode: Define a one-to-many dependency on object keys. When the state of an object changes, all objects that depend on it will be notified and updated by braking, such as the implementation of listener in Spring-ApplicationListener

6. What is a SpringIOC container

Inversion of Control is IoC (Inversion of Control), which transfers the calling rights of objects that are traditionally directly manipulated by program code to the container, and the assembly and management of object components are realized through the container. The so-called "inversion of control" concept is the transfer of control over component objects, from the program code itself to the external container.

Spring IOC is responsible for creating objects, managing objects (through dependency injection (DI), assembling objects, configuring objects, and managing the entire life cycle of these objects)

7. Advantages of IOC

  • IOC or dependency injection minimizes the amount of application code
  • It makes the application easy to test, unit testing no longer requires singleton and JNDI lookup mechanism
  • Minimal cost and minimal intrusiveness make loose coupling possible
  • The IOC container supports hungry initialization and lazy loading when loading services

8. Implementation mechanism of Spring IOC

The implementation principle of IOC in Spring is the factory mode plus reflection mechanism

interface Fruit {
    
    
   public abstract void eat();
 }

class Apple implements Fruit {
    
    
    public void eat(){
    
    
        System.out.println("Apple");
    }
}

class Orange implements Fruit {
    
    
    public void eat(){
    
    
        System.out.println("Orange");
    }
}

class Factory {
    
    
    public static Fruit getInstance(String ClassName) {
    
    
        Fruit f=null;
        try {
    
    
            f=(Fruit)Class.forName(ClassName).newInstance();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return f;
    }
}

class Client {
    
    
    public static void main(String[] a) {
    
    
        Fruit f=Factory.getInstance("io.github.dunwu.spring.Apple");
        if(f!=null){
    
    
            f.eat();
        }
    }
}

9. What is the difference between BeanFactory and ApplicationContext

BeanFactory and ApplicationContext are the two core interfaces of Spring, and both can be used as Spring containers. The ApplicationContext is a sub-interface of BeanFactory.

Dependency

BeanFactory: It is the lowest-level interface in Spring. It contains definitions of various Beans, reads bean configuration documents, manages bean loading and instantiation, controls bean life cycle, and maintains dependencies between beans.

As a derivation of BeanFactory, ApplicationContext interface not only provides the functions of BeanFactory, but also provides more complete framework functions:

  • Inherit MessageSource, so it supports internationalization.
  • Unified resource file access method.
  • Provides events for registering beans in the listener.
  • Load multiple configuration files at the same time.
  • Load multiple (inherited) contexts, so that each context focuses on a specific level, such as the web layer of the application.

Loading method

BeanFactroy uses lazy loading to inject Beans, that is, only when a Bean is used (getBean() is called), the Bean is loaded and instantiated. In this way, we cannot find some existing Spring configuration problems. If a certain attribute of Bean is not injected, after BeanFacotry is loaded, an exception will not be thrown until the getBean method is called for the first time.

ApplicationContext, which creates all Beans at once when the container is started. In this way, when the container starts, we can find configuration errors in Spring, which is conducive to checking whether the dependent properties are injected. After the ApplicationContext starts, all single-instance beans are pre-loaded. By pre-loading single-instance beans, you can ensure that when you need them, you don't have to wait because they have already been created.

Compared with the basic BeanFactory, the only disadvantage of ApplicationContext is memory space. When there are many application configuration beans, the program startup is slower.

Create method

BeanFactory is usually created programmatically, ApplicationContext can also be created in a declarative way, such as using ContextLoader.

way to register

Both BeanFactory and ApplicationContext support the use of BeanPostProcessor and BeanFactoryPostProcessor, but the difference between the two is: BeanFactory needs to be manually registered, while ApplicationContext is automatically registered.

10. What is the usual implementation of ApplicationContext

FileSystemXmlApplicationContext : This container loads the definition of beans from an XML file, and the full path name of the XML Bean configuration file must be provided to its constructor.

ClassPathXmlApplicationContext : This container also loads the definition of beans from an XML file. Here, you need to set the classpath correctly because this container will find the bean configuration in the classpath.

WebXmlApplicationContext : This container loads an XML file that defines all beans of a WEB application.

11. The scope of several beans supported by Spring

  • singleton: bean has only one instance in each Spring IOC container
  • prototype: A bean definition can have multiple instances
  • request: Each http request will create a bean, the scope is only valid in the context of web-based Spring ApplicationContext
  • session: In an http session, a bean definition corresponds to an instance, and the scope is only valid in the context of web-based Spring ApplicationContext
  • global-session: In a global Http Session, a bean definition corresponds to an instance, and the scope is only valid in the context of a web-based Spring ApplicationContext

12. Is the singleton bean in the Spring framework thread safe?

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

The bean in spring is in singleton mode by default, and the spring framework does not encapsulate singleton beans in multiple threads.

In fact, most of the time SpringBean is stateless, so to some extent, the bean is also safe, but if the bean is stateful, the developer needs to ensure the safety of the thread. The easiest way is to change the bean. The scope of "singleton" is changed to prototype, so that the request bean is equivalent to new Bean(), so thread safety can be guaranteed

  • Stateful, refers to the data storage function
  • Stateless, which means that data will not be saved

13. How does Spring deal with thread concurrency issues

In general, only stateless beans can be shared in a multithreaded environment. In Spring, most beans can be declared as singleton scope, because Spring uses ThreadLocal to handle non-thread-safe states in some beans. Solve thread safety issues.

ThreadLocal and thread synchronization mechanism are both to solve the problem of access conflicts of the same variable in multiple threads. The synchronization mechanism adopts the "time for space" approach, and only provides one variable. Different threads need to acquire locks before accessing them, and threads that have not acquired locks need to be queued. And ThreadLocal uses the "space for time" approach.

ThreadLocal will provide an independent variable copy for each thread, thereby isolating the data access conflicts of multiple threads. Because each thread has its own copy of the variable, there is no need to synchronize the variable. ThreadLocal provides thread-safe shared objects. When writing multi-threaded code, unsafe variables can be encapsulated in ThreadLocal

14. What is AOP

AOP aspect-oriented programming is complementary to traditional OOP. In OOP, we use classes as our basic unit, while the basic unit in AOP is the aspect. The key to the realization of AOP lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy

1. AspectJ is an enhancement of the static proxy. AOP proxy classes are generated during the compilation phase, so it is also called compile-time enhancement. It will weave AspectJ into the java bytecode during the compilation phase

2. The dynamic proxy used by SpringAOP. The dynamic proxy does not modify the bytecode, but temporarily generates an AOP object in memory each time it runs. This AOP object contains all the methods of the target object and is at a specific point of cut. Enhanced

15. What is the bottom layer of SpringAOP?

The bottom layer of SpringAOP is implemented based on dynamic proxy. There are two types of dynamic proxy, one is dynamic proxy based on JDK, and the other is dynamic proxy based on cglib. There is no default dynamic proxy mode selected in Spring AOP, but based on whether the object being proxied is a class or an interface.

If it is an interface, the dynamic proxy of JDK is used; if it is a class, the dynamic proxy of cglib is used

16. How to configure metadata for Spring container? (That is to create a Bean)

1. Based on XML configuration file

<!-- id可以理解为对象名 -->
<bean id="" class="">
</bean>

2. Annotation-based configuration

@Controller
@Service
@Resposity

//开启注解配置
<context: annotation-config/>

3. Java-based configuration

@Confirguration@Bean搭配使用

17. Several ways of dependency injection

Dependency injection is actually to assign an initial value to the attribute value in our object

Implementation based on xml configuration file

1. Constructor injection

2. Setter injection

3. Interface injection

18. How to use @Required annotation

@Required applies the setter method of the bean property. This annotation indicates that the attribute value of the field must have, if not, an exception will be thrown

19、@Autowired、@Resource、@Qualifier

@Autowired, automatic assembly according to type

@Resourcee, automatically assemble according to the name, and then assemble according to the type

@Qualifier, when there are multiple beans of the same type, and you want to assemble only one of the beans using attributes, you can use @Qualifier and @Autowired annotations together

20, the difference between BeanFactory and FactoryBean

BeanFactory is a Factory, that is, IOC container or object factory, and FactoryBean is a Bean. In Spring, all Beans are managed by the BeanFactory (that is, the IOC container). But for FactoryBean, this Bean is not a simple Bean, but a factory Bean that can produce or modify object generation. Its implementation is similar to the factory pattern and decorator pattern in the design pattern

21. The process of a bean assembly in Spring

Guess you like

Origin blog.csdn.net/weixin_54707168/article/details/113976977