[Make a wish offer] Spring interview questions summary (with answers)

Foreword:

Insert picture description here

Spring is an open source development framework for java enterprise applications. Spring is mainly used to develop Java applications, but some extensions are aimed at building web applications on the J2EE platform. The goal of the Spring framework is to simplify the development of Java enterprise applications and to promote good programming habits through a POJO-based programming model.

In addition, I have compiled and collected more than 20 years of company interview knowledge points, as well as various Java core knowledge points for free to share with you. The following are just some screenshots. If you want information, you can also click 795983544 to receive the secret code CSDN.

Insert picture description here

1. What are the benefits of using the Spring framework

  • Lightweight: Spring is lightweight, the basic version is about 2MB.
  • Inversion of control: Spring achieves loose coupling through inversion of control. Objects give their dependencies instead
    of creating or finding dependent objects.
  • Aspect-oriented programming (AOP): Spring supports aspect-oriented programming and
    separates application business logic from system services.
  • Container: Spring contains and manages the life cycle and configuration of objects in the application.
  • MVC framework: Spring's WEB framework is a well-designed framework and a good alternative to Web frameworks.
  • Transaction management: Spring provides a continuous transaction management interface, which can be extended from local transactions to
    global transactions (JTA).
  • Exception handling: Spring provides a convenient API to convert specific technology-related exceptions (such as thrown by JDBC, Hibernate or JDO) into consistent unchecked exceptions.

2. What is the Spring IOC container?

The core of the Spring framework is the Spring container. The container creates objects, assembles them, configures them, and manages their complete life cycle. The Spring container uses dependency injection to manage the components that make up the application. The container receives instructions for instantiation, configuration and assembly of objects by reading the provided configuration metadata. The metadata can be provided through XML, Java annotations or Java code.

Insert picture description here

3. How many ways can dependency injection be accomplished?

Generally, dependency injection can be done in three ways, namely:

Constructor injection

setter injection

Interface injection

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

4. The implementation mechanism of Spring IoC.

The realization principle of IoC in Spring is the factory pattern plus reflection mechanism.
Example:

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();
        }
    }
}

5. What is a spring bean?

They are the objects that form the backbone of the user's application.

Beans are managed by the Spring IoC container.

They are instantiated, configured, assembled and managed by the Spring IoC container.

Bean is created based on the configuration metadata provided by the user to the container.

6. What configuration methods does spring provide?

Based on xml configuration

The dependencies and services required by the bean are specified in the configuration file in XML format. These configuration files usually contain many bean definitions and application-specific configuration options. They usually start with the bean tag. E.g:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
        <property name="name" value="Edureka"></property>
    </bean>

Configuration based on annotations

Instead of using XML to describe bean assembly, you can configure the bean as the component class itself by using annotations on related class, method, or field declarations. By default, annotation assembly is not turned on in the Spring container. Therefore, you need to enable it in the Spring configuration file before using it. E.g:

<beans>
      <context:annotation-config/>
      <!-- bean definitions go here -->
  </beans>

Configuration based on Java API

Spring's Java configuration is achieved by using @Bean and @Configuration.

  • The @Bean annotation plays the same role as the <bean /> element.
  • The @Configuration class allows you to define inter-bean dependencies by simply calling other @Bean methods in the same class.

E.g:

public class StudentConfig {
    
       
    @Bean
    public StudentBean myStudent() {
    
    
        return new StudentBean();
    }
}

7. What is the life cycle of the spring bean container?

The life cycle process of the spring bean container is as follows:

  • The Spring container instantiates the bean according to the bean definition in the configuration.
  • Spring uses dependency injection to fill in all properties, such as the configuration defined in the bean.
  • If the bean implements the BeanNameAware interface, the factory calls setBeanName() by passing the bean ID.
  • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory() by passing an instance of itself.
  • If there are any BeanPostProcessors associated with the bean, call the
    preProcessBeforeInitialization() method.
  • If an init method (the init-method attribute of <bean>) is specified for the bean, it will be called.
  • Finally, if there are any BeanPostProcessors associated with the bean, the
    postProcessAfterInitialization() method will be called .
  • If the bean implements the DisposableBean interface, destroy() will be called when the spring container is closed.
  • If the destroy method (destroy-method attribute of <bean>) is specified for the bean, it will be called.
    Insert picture description here

8. What are spring internal beans?

The bean can only be declared as an inner bean if it is used as a property of another bean. In order to define beans, Spring's XML-based configuration metadata provides the use of the <bean> element in the <property> or <constructor-arg>. Inner beans are always anonymous, they are always used as prototypes.

For example, suppose we have a Student class, which references the Person class. Here we will only create an instance of the Person class and use it in Student.

Student.java

public class Student {
    
    
    private Person person;
    //Setters and Getters
}
public class Person {
    
    
    private String name;
    private String address;
    //Setters and Getters
}
bean.xml

<bean id=“StudentBean" class="com.edureka.Student">
        <property name="person">
            <!--This is inner bean -->
            <bean class="com.edureka.Person">
                <property name="name" value=“Scott"></property>
                <property name="address" value=“Bangalore"></property>
            </bean>
        </property>
    </bean>

9. What is spring assembly

When beans are grouped together in the Spring container, it is called assembly or bean assembly. The Spring container needs to know what beans are needed and how the container should use dependency injection to bind the beans together and assemble the beans.

10. What are the methods of automatic assembly?

The Spring container can automatically assemble beans. In other words, you can let Spring automatically resolve bean collaborators by checking the contents of the BeanFactory.

Different modes of automatic assembly:

  • no-This is the default setting, which means there is no automatic assembly. You should use explicit bean references for assembly.
  • byName-It injects object dependencies based on the name of the bean. It matches and assembles beans whose attributes are defined by the same names in the XML file.
  • byType-It injects object dependencies based on type. If the type of the attribute matches a bean name in the XML file, the attribute is matched and assembled.
  • Constructor-It injects dependencies by calling the constructor of the class. It has a large number of parameters.
  • autodetect-First, the container tries to use autowire assembly through the constructor, if not, it tries to auto-assemble through byType.

11. What are the limitations of automatic assembly?

  • Possibility of overwriting-you can always use and set specified dependencies, which will override autowiring.
  • Basic metadata types-simple attributes (such as original data types, strings, and classes) cannot be automatically assembled.
  • Confusing nature-always prefer to use explicit assembly, because automatic assembly is not very precise.

12. What important Spring annotations have you used?

@Controller-The controller class used in the Spring MVC project.

@Service-for service classes.

@RequestMapping-Used to configure URI mapping in the controller handler method.

@ResponseBody-used to send Object as response, usually used to send XML or JSON data as response.

@PathVariable-Used to map dynamic values ​​from URI to handler method parameters.

@Autowired-Used to autowire dependencies in spring beans.

@Qualifier-Use @Autowired annotation to avoid confusion when there are multiple bean type instances.

@Scope-Used to configure the scope of spring beans.

@Configuration, @ComponentScan and @Bean-for java based configuration.

@Aspect, @Before, @After, @Around, @Pointcut-for aspect programming (AOP).

13. What is the difference between @Component, @Controller, @Repository, @Service?

@Component: This marks the java class as bean. It is a general stereotype for any Spring management component. Spring's component scanning mechanism can now pick it up and pull it into the application environment.

@Controller: This marks a class as a Spring Web MVC controller. Beans marked with it will be automatically imported into the IoC container.

@Service: This annotation is a specialization of component annotation. It does not provide any other behavior for the @Component annotation. You can use @Service instead of @Component in the service layer class because it specifies the intent in a better way.

@Repository: This annotation is a specialization of the @Component annotation with similar uses and functions. It provides additional benefits for DAO. It imports DAO into the IoC container and makes unchecked exceptions eligible to be converted to Spring DataAccessException.

14. What is the use of @Required annotation?

@Required is applied to bean property setter methods. This annotation only indicates that you must use explicit property values ​​in the bean definition or use autowiring to populate the affected bean properties during configuration. If the affected bean properties have not been populated, the container will throw a BeanInitializationException.

public class Employee {
    
    
    private String name;
    @Required
    public void setName(String name){
    
    
        this.name=name;
    }
    public string getName(){
    
    
        return name;
    }
}

15. What is the use of @Autowired annotation?

@Autowired can more accurately control where and how the automatic assembly should be performed. This annotation is used to automatically assemble beans on setter methods, constructors, properties or methods with arbitrary names or multiple parameters. By default, it is type-driven injection.

public class Employee {
    
    
    private String name;
    @Autowired
    public void setName(String name) {
    
    
        this.name=name;
    }
    public string getName(){
    
    
        return name;
    }
}

16.List the transaction management types supported by spring

Spring supports two types of transaction management:

Programmatic transaction management: During this process, affairs are managed with the help of programming. It offers you great flexibility, but it is very difficult to maintain.

Declarative transaction management: Here, transaction management is separated from business code. Only use annotations or XML-based configuration to manage transactions.

Which ORM frameworks spring supports
Hibernate

iBatis

JPA

JDO

OJB

17. What is the difference between constructor injection and set value injection

Please note the following obvious differences:

(1) Setting value injection supports most dependency injections. If we only need to inject int, string and long variables, do not use setting method injection. For basic types, if there is no injection, you can set default values ​​for the basic types. Constructor injection does not support most dependency injection, because the correct constructor parameters must be passed in when the constructor is called, otherwise an error will be reported.
(2) Set value injection will not rewrite the value of the constructor. If we use both constructor injection and setting injection for the same variable, then the constructor will not be able to cover the value injected by the setting. Obviously, because the constructor is only called when the object is created.
(3) When setting value injection is used, it is not guaranteed whether a certain dependency has been injected, that is, the dependency of the object may be incomplete at this time. In another case, constructor injection does not allow the generation of objects with incomplete dependencies.
(4) If object A and object B depend on each other during value injection, Spring will throw ObjectCurrentlyInCreationException when creating object A, because object A cannot be created before object B is created, and vice versa. Spring uses setting injection to solve the circular dependency problem, because the setting method of an object is called before the object is created.

18.Spring aspect-oriented programming (AOP)

What is AOP

OOP (Object-Oriented Programming) object-oriented programming allows developers to define vertical relationships, but it is not suitable for defining horizontal relationships, resulting in a lot of code duplication, which is not conducive to the reuse of various modules.

AOP (Aspect-Oriented Programming), generally referred to as aspect-oriented programming, as a supplement to object-oriented, used to extract and encapsulate common behaviors and logic that have nothing to do with business but have an impact on multiple objects Reusable module, this module is named "Aspect", reducing the repetitive code in the system, reducing the coupling between modules, and improving the maintainability of the system. Can be used for authority authentication, log, transaction processing, etc.

What is the difference between Spring AOP and AspectJ AOP? What are the ways to implement AOP?

The key to the realization of AOP lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy. The representative of static proxy is AspectJ; the representative of dynamic proxy is Spring AOP.

(1) AspectJ is an enhancement of static proxy. The so-called static proxy means that the AOP framework will generate AOP proxy classes during the compilation phase, so it is also called compile-time enhancement. It will weave AspectJ (aspects) into Java bytes during the compilation phase In the code, it is the enhanced AOP object when it runs.

(2) The dynamic proxy used by Spring AOP. The so-called dynamic proxy means that the AOP framework does not modify the bytecode, but temporarily generates an AOP object for the method in memory each time it runs. This AOP object contains the target object All methods of, and enhanced processing at specific pointcuts, and callback methods of the original object.

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

  1. Proxy mode: It is used more in AOP and remoting.

  2. Singleton mode: The bean defined in the spring configuration file defaults to the singleton mode.

  3. Template method pattern: used to solve the problem of code duplication.

  4. Front controller mode: Spring provides DispatcherServlet to distribute requests.

  5. Dependency injection mode: runs through the core concept of the BeanFactory / ApplicationContext interface.

  6. Factory pattern: BeanFactory is used to create instances of objects.

What is the core of springmvc, how is the request process handled, and how is the inversion of control achieved?

Core: Inversion of Control and Aspect Oriented

Request processing flow:

  • First, the user sends a request to the front controller, and the front controller decides which page controller to select for processing according to the request information (such as URL) and delegates the request to it, which is the control logic part of the previous controller;
  • After the page controller receives the request, it performs functional processing. First, it needs to collect and bind the request parameters to an object, and verify it, and then delegate the command object to the business object for processing; after processing, it returns a ModelAndView (model data and logic View name);
  • The front controller takes back control, and then selects the corresponding view for rendering according to the returned logical view name, and passes the model data to the view for rendering;
  • The front controller takes back control again and returns the response to the user.

How to achieve inversion of control:

Every time we use the spring framework, we must configure the xml file, this xml configures the id and class of the bean.
The default bean in spring is single-instance mode, and this instance can be created through the bean's class reference reflection mechanism.
Therefore, the spring framework creates instances for us through reflection and maintains them for us.
A needs to reference class B, and the spring framework will pass the reference of the B instance to the member variable of A through xml.

to sum up:

No matter which company it is, it attaches great importance to the Spring framework technology and the foundation, so don't underestimate any knowledge. The interview is a two-way selection process. Don't go to the interview with a fearful attitude, which is not conducive to your own performance. At the same time, you should not only look at salary, but also whether you really like this company and whether you can really get exercise. In fact, I have written so much, but my own summary, not necessarily applicable to everyone, I believe that after some interviews, everyone will have these feelings.

In addition, I have compiled and collected more than 20 years of company interview knowledge points, as well as various Java core knowledge points for free to share with you. The following are just some screenshots. If you want information, you can also click 795983544 to receive the secret code CSDN.

Insert picture description here

Guess you like

Origin blog.csdn.net/banzhuanhu/article/details/108562931