Java in the common spring interview problem TOP50

Source: Internet
Author: User
Tags aop stomp

1. General Questions

1.1. What are the main features of different versions of the Spring Framework ?

Version Feature

    • Spring 2.5 was released on 2007. This is the first version that supports annotations.
    • Spring 3.0 was released on 2009. It takes full advantage of the improvements in JAVA5 and provides support for JEE6.
    • Spring 4.0 was released on 2013. This is the first version that fully supports JAVA8.

1.2. What is the Spring Framework?

    • Spring is an open-source application framework designed to reduce the complexity of application development.
    • It is lightweight and loosely coupled.
    • It has a layered architecture that allows users to select components while also providing a cohesive framework for Java EE application development.
    • It can integrate other frameworks, such as Structs, Hibernate, EJB, etc., so it is also called framework framework.

1.3. Enumerate The advantages of the Spring Framework.

    • Thanks to the layered architecture of Spring frameworks, users are free to choose the components they need.
    • The Spring Framework supports POJO (Plain old Java Object) programming for continuous integration and testability.
    • JDBC is simplified because of dependency injection and control inversion.
    • It is open source for free.

1.4. What are the different features of the Spring Framework?

    • Lightweight-Spring is lightweight in terms of both code volume and transparency.
    • IOC-Control reversal
    • AOP-aspect-oriented programming separates the application business logic from the system services for high cohesion.
    • Container-Spring is responsible for creating and managing the life cycle and configuration of objects (beans).
    • MVC-Provides a highly configurable Web application and facilitates the integration of other frameworks.
    • Transaction management-Provides a common abstraction layer for transaction management. Spring's transactional support can also be used in environments with fewer containers.
    • JDBC Exception-The Spring's JDBC Abstraction layer provides an exception hierarchy that simplifies error handling strategies.

1.5. How many modules are there in the Spring Framework, and what are they?

①, Spring core container – this layer is essentially the core of the spring Framework. It contains the following modules:

    • Spring Core
    • Spring Bean
    • Spel (Spring Expression Language)
    • Spring Context

②, data access/integration – This layer provides support for interacting with the database. It contains the following modules:

    • JDBC (Java DataBase Connectivity)
    • ORM (Object relational Mapping)
    • OXM (Object XML mappers)
    • JMS (Java Messaging Service)
    • Transaction

③, Web – This layer provides support for creating WEB applications. It contains the following modules:

    • Web
    • Web–servlet
    • Web–socket
    • Web–portlet

④, aop– This layer supports tangent-oriented programming

⑤, instrumentation– This layer provides support for class detection and class loader implementations.

⑥, test– This layer is supported for testing with JUnit and TestNG.

⑦, several miscellaneous modules:

    • messaging– This module provides support for STOMP. It also supports the annotation programming model, which is used to route and process STOMP messages from WebSocket clients.
    • aspects– This module provides support for integration with AspectJ.

1.6. What is a Spring configuration file?

The Spring configuration file is an XML file. This file mainly contains class information. It describes how these classes are configured and introduced to each other. However, the XML configuration file is verbose and cleaner. If not properly planned and written, managing in large projects becomes very difficult.

1.7. What are the different components of the Spring application?

Spring applications typically have the following components:

    • interface-defines the function.
    • Bean class-It contains attributes, setter and Getter methods, functions, and so on.
    • Spring aspect-oriented programming (AOP)-provides feature-oriented programming for facets.
    • Bean configuration file-Contains information about the classes and how to configure them.
    • User program-it uses interfaces.

1.8. What are the ways to use Spring ?

    • There are several ways to use Spring:
    • As a mature Spring Web application.
    • As a third-party WEB framework, use the Spring frameworks middle tier.
    • For remote use.
    • As an enterprise Java Bean, it can wrap an existing POJO (Plain old Java Objects).

2. Dependency Injection (Ioc)

2.1. What is a Spring IOC container?

The core of the spring framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their full lifecycles. The Spring container uses dependency injection to manage the components that make up the application. A container receives an object for instantiation, configuration, and assembly instructions by reading the provided configuration metadata. This metadata can be provided through Xml,java annotations or Java code

2.2. What is dependency injection?

In dependency injection, you do not have to create objects, but you must describe how to create them. Instead of connecting components and services directly in your code, you describe which components in the configuration file require which services. They are assembled together by the IoC container.

2.3. How many ways can you complete dependency injection?

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

    • Constructor injection
    • Setter Injection
    • Interface Injection

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

2.4. differentiate between constructor injection and setter injection.

2.5. How many IOC containers are there in spring ?

    • Beanfactory-beanfactory is like a factory class that contains a collection of beans. It instantiates the bean when requested by the client.
    • The Applicationcontext-applicationcontext interface extends the Beanfactory interface. It provides some additional functionality on a beanfactory basis.

2.6. differentiate between beanfactory and applicationcontext.

2.7. Enumerate Some of the benefits of the IoC.

Some of the IoC's benefits are:

    • It minimizes the amount of code in the application.
    • It will make your application easy to test because it does not require any singleton or JNDI lookup mechanisms in the unit test case.
    • It facilitates loose coupling with minimal impact and minimal intrusion mechanisms.
    • It supports immediate instantiation and lazy loading services.

2.8. The implementation mechanism of Spring IoC.

The IoC implementation principle in Spring is the Factory mode plus reflection mechanism.

Example:

3. Beans

3.1. What is a spring bean?

    • They are objects that form the backbone of the user application.
    • Beans are managed by the Spring IoC container.
    • They are instantiated, configured, assembled, and managed by the Spring IoC container.
    • Beans are created based on the configuration metadata that the user provides to the container.

3.2. What are the configuration methods provided by spring?

    • Based on XML configuration

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

    • Annotation-based configuration

Instead of using XML to describe the bean assembly, you can configure the Bean as the component class itself by using annotations on related classes, methods, or field declarations. By default, note Assembly is not open in the Spring container. Therefore, you need to enable it in the Spring configuration file before you use it. For example:

    • Java API-based configuration

The Java configuration for Spring is implemented by using @Bean and @Configuration.

    1. @Bean annotations Play the same role as elements.
    2. @Configuration class allows you to define inter-Bean dependencies by simply invoking other @Bean methods in the same class.

For example:

3.3. Spring supports centralized bean scope?

Spring Beans Support 5 Types of scopes:

    • Singleton-There is only one single instance per Spring IoC container.
    • Prototype-Each request results in a new instance.
    • Request-Every HTTP request produces a new instance, and the bean is valid only within the current HTTP request.
    • Session-Every HTTP request produces a new bean, and the bean is valid only within the current HTTP session.
    • Global-session-Similar to the standard HTTP session scope, but it only makes sense in portlet-based Web applications. The Portlet specification defines the concept of a global Session, which is shared by all the various portlets that make up a portlet Web application. The bean defined in the global session scope is limited to the lifetime of the world Portlet session. If you use the global session scope to identify the bean in the Web, the Web is automatically used as the session type.

The last three are available only if the user is using a WEB-enabled ApplicationContext.

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

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

    1. The Spring container instantiates the bean based on the bean definition in the configuration.
    2. Spring populates all properties with dependency injection, such as the configuration defined in the bean.
    3. If the bean implements the Beannameaware interface, the factory calls Setbeanname () by passing the Bean's ID.
    4. If the bean implements the Beanfactoryaware interface, the factory invokes Setbeanfactory () by passing an instance of itself.
    5. If there is any beanpostprocessors associated with the Bean, the Preprocessbeforeinitialization () method is called.
    6. If you specify the Init method (the Init-method property) for the bean, it is called.
    7. Finally, if there are any beanpostprocessors associated with the Bean, the Postprocessafterinitialization () method is called.
    8. If the bean implements the Disposablebean interface, Destory () is called when the spring container is closed.
    9. If the Destroy method (the Destroy-method property) is specified for the bean, it is called.

3.5. What is Spring 's internal bean?

A bean can be declared as an internal bean only if it is used as a property of another bean. In order to define XML-based configuration metadata for bean,spring, the use of elements is provided in or. Internal beans are always anonymous, and they are always used as prototypes.

For example, suppose we have a Student class that references the person class. Here we will just create an instance of the person class and use it in Student.

Student.java

Bean.xml

3.6. What is Spring Assembly

When a bean is grouped together in a Spring container, it is called an assembly or a 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.

3.7. What are the options for automatic assembly?

Spring containers can automatically assemble beans. That is, you can let Spring automatically parse the bean's collaborators by examining the contents of the beanfactory.

Different modes of automatic assembly:

    • No-this is the default setting, which means no automatic assembly. Assembly should be made using an explicit bean reference.
    • ByName-It injects an object dependency based on the name of the bean. It matches and assembles its properties with the bean defined by the same name in the XML file.
    • Bytype-It injects an object dependency based on the type. If the type of the property matches one of the bean names in the XML file, the property is matched and assembled.
    • constructor-it injects a dependency by invoking the constructor of the class. It has a large number of parameters.
    • AutoDetect-First the container tries to assemble using the Autowire through the constructor, and if not, it tries to assemble automatically through the bytype.

3.8. What are the limitations of automatic assembly?

    • Coverage possibilities-you can always use and set a specified dependency, which overrides automatic assembly.
    • Basic metadata types-simple attributes such as the original data type, strings, and classes cannot be automatically assembled.
    • Confusing nature-always prefer to use clear assembly, because automatic assembly is less precise.

4. Annotations

4.1. What is annotation-based container configuration

Instead of using XML to describe the bean assembly, the developer moves the configuration to the component class itself by using annotations on related classes, methods, or field declarations. It can be used as an alternative to XML settings. For example:

The Java configuration for Spring is implemented by using @Bean and @Configuration.

    • @Bean annotations Play the same role as elements.
    • @Configuration class allows you to define inter-Bean dependencies by simply invoking other @Bean methods in the same class.

For example:

4.2. How do I start the annotation assembly in spring?

By default, note Assembly is not open in the Spring container. Therefore, to use annotation-based assembly, we must enable it in the Spring configuration file through the configuration element.

4.3. @Component, @Controller, @Repository, What's the difference between @Service?

    • @Component: This marks the Java class as a bean. It is a generic stereotype of 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. The Bean labeled with it is automatically imported into the IoC container.
    • @Service: This annotation is the specificity of the component annotations. It does not provide any other behavior for @Component annotations. You can use @Service instead of ④[email protected] in a service-tier class, because it specifies the intent in a better way.
    • @Repository: This annotation is a special feature of @Component annotations with similar uses and functions. It provides additional benefits for DAO. It imports DAO into the IoC container and makes the unchecked exception eligible to be converted to Spring DataAccessException.

4.4. What is the use of @Required annotations?

@Required applied to the Bean property setter method. This annotation only indicates that an explicit attribute value in the bean definition must be used at configuration time or the affected bean properties are populated with automatic assembly. If the affected bean properties have not been populated, the container throws beaninitializationexception.

Example:

4.5. What is the use of @Autowired annotations?

@Autowired can more accurately control where and how automated assembly should be done. This annotation is used to automatically assemble beans on a setter method, a constructor, a property or method that has any name or multiple parameters. By default, it is type-driven injection.

4.6. What is the use of @Qualifier annotations?

When you create multiple beans of the same type and want to assemble only one of the beans using attributes, you can use @qualifier annotations and @Autowired to disambiguate by specifying which exact bean should be assembled.

For example, here we have two classes, Employee and Empaccount, respectively. In Empaccount, using @qualifier specifies that a bean with ID EMP1 must be assembled.

Employee.java

Empaccount.java

4.7. What is the use of @RequestMapping annotations?

@RequestMapping annotations are used to map specific HTTP request methods to specific classes/methods in the controller that will handle the corresponding request. This note can be applied to two levels:

    • Class level: The URL of the map request
    • Method level: Map URLs and HTTP request methods

5. data Access

5.1. What is the use of spring DAO?

Spring DAO makes it easier for data access technologies such as jdbc,hibernate or JDO to work in a uniform way. This makes it easy for users to switch between persistent technologies. It also allows you to write code without having to think about capturing different exceptions for each technique.

5.2. enumerates The exceptions that Spring DAO throws.

5.3. What classes exist in the spring JDBC API?

    • JdbcTemplate
    • Simplejdbctemplate
    • Namedparameterjdbctemplate
    • Simplejdbcinsert
    • Simplejdbccall

5.4. What are the methods for using Spring to access Hibernate?

We can use Spring to access Hibernate in two ways:

    1. Control inversion using Hibernate templates and callbacks
    2. Extend Hibernatedaosupport and apply an AOP interceptor node

5.5. enumerating The types of transaction management supported by Spring

Spring supports two types of transaction management:

①. Programmatic transaction management: In this process, you manage transactions with the help of programming. It gives you great flexibility, but it's very difficult to maintain.

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

5.6. What ORM frameworks are supported by spring

    • Hibernate
    • IBatis
    • Jpa
    • Jdo
    • Ojb

6. AOP

6.1. What is AOP?

AOP (aspect-oriented programming), which is aspect-oriented programming , complements OOP (object-oriented programming, object-oriented programming) and provides an abstract software architecture that differs from OOP 's perspective.

In OOP, we use class as our basic unit, while the basic unit in AOP is Aspect ( tangent )

6.2. What is Aspect?

Aspect consists of pointcount and advice, which contains both the definition of the crosscutting logic and the definition of the connection point. Spring AOP is the framework for implementing facets that weave the crosscutting logic defined by the facets into the connection points specified by the facets.

The focus of AOP's work is on how to enhance the knitting target's connection point, which consists of two jobs:

    1. How to navigate to a specific joinpoint via pointcut and advice
    2. How to write slice code in advice.

It is easy to think that , Use @Aspect The annotated class is the tangent plane .

6.3. What is a tangent point (joinpoint)

Some point in time at which a program runs, such as the execution of a method, or the handling of an exception.

In Spring AOP, join points is always the point of execution of the method.

6.4. What is notification (Advice)?

The action taken by Aspect at a particular joinpoint is called Advice. Spring AOP uses a Advice as an interceptor to maintain a series of interceptors around the joinpoint.

6.5. What types of notifications are available (Advice)?

    • Before-these types of Advice are performed before the Joinpoint method and are configured with @Before annotation tags.
    • After returning-these types of Advice are executed after the connection point method is performed normally and configured with the @afterreturning annotation tag.
    • After throwing-these types of Advice are executed only when the Joinpoint method exits by throwing an exception and uses @AfterThrowing annotation tag configuration.
    • After (finally)-these types of Advice are executed after the connection point method, regardless of whether the method exit is normal or abnormal, and is configured with @After annotation tags.
    • Around-These types of Advice are executed before and after the connection point and are configured with @Around annotation tags.

6.6. points out that in spring AOP concern and cross-cutting concern the difference between them.

Concern is the behavior we want to define in a particular module of the application. It can be defined as the function we want to implement.

Cross-cutting concern is a behavior that applies to the entire application, which affects the entire application. For example, logging, security, and data transfer are issues of concern to almost every module in the application, so they are cross-cutting issues.

6.7. What are the implementation methods of AOP?

The techniques for implementing AOP are divided into two major categories:

①. Static proxy-refers to compiling using the commands provided by the AOP framework to generate an AOP proxy class at compile time, which is also referred to as compilation enhancement;

A. Compile-time weaving (special compiler Implementation)

B. Class load-time weaving (special class loader implementation).

②. Dynamic Proxy-Generates an AOP dynamic proxy class in memory at run time, and is also known as run-time enhancement.

C.JDK Dynamic Agent

D.cglib

6.8. What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is based on dynamic proxy, and AspectJ is implemented based on static proxy method.

Spring AOP supports only method-level PointCut, provides full AOP support, and supports attribute-level PointCut.

6.9. How do I understand The agents in Spring?

The object created after applying Advice to the target object is called a proxy. In the case of the client object, the target object and the proxy object are the same.

Advice + targetobject=proxy

6.10. What is knitting (Weaving)?

To create a advice object, link to a aspect and other application type or object, called weaving (Weaving). In Spring AOP, weaving is performed at run time. Please refer to:

7. MVC

7.1. What is the use of the Spring MVC framework?

The Spring Web MVC Framework provides model - view - controller Architecture and ready-to-use components for developing flexible and loosely coupled Web applications. The MVC pattern helps to separate different aspects of an application, such as input logic, business logic, and UI logic, while providing loose coupling between all of these elements.

7.2. describe the workflow of Dispatcherservlet

Dispatcherservlet's workflow can be illustrated with a picture

    • Sends an HTTP request to the server, and the request is captured by the front controller dispatcherservlet.
    • Dispatcherservlet the requested resource Identifier (URI) based on the configuration of the -servlet.xml to parse the URL of the request. Then, based on the URI, call handlermapping to get all the related objects of the Handler configuration (including the Handler object and the interceptor corresponding to the Handler object), and finally return as a Handlerexecutionchain object.
    • Dispatcherservlet according to the obtained handler, choose a suitable handleradapter. (Note: If Handleradapter is successfully obtained, the Interceptor Prehandler (...) will start executing. method).
    • Extract the model data from the request, populate the handler entry, and start executing the handler (Controller). In the process of populating the handler, depending on your configuration, Spring will do some extra work for you:
    1. Httpmessageconveter: Converts a request message (such as Json, XML, and so on) into an object, converting the object to the specified response information.
    2. Data transformation: Data conversion for a request message. such as string conversion to Integer, double, and so on.
    3. Data is initialized: Data is formatted for the request message. such as converting a string into a formatted number or a formatted date.
    4. Data validation: Verify the validity of the data (length, format, etc.), and verify that the results are stored in Bindingresult or error.
    • When the Handler (Controller) executes, returns a Modelandview object to Dispatcherservlet;
    • Based on the returned Modelandview, select a suitable viewresolver (must be viewresolver already registered in the Spring container) to return to Dispatcherservlet.
    • Viewresolver combines model and view to render the view.
    • The view is responsible for returning the rendered result to the client.

7.3. introduce webapplicationcontext

Webapplicationcontext is an extension of applicationcontext. It has some of the extra features required by the WEB application. It differs from ordinary applicationcontext in the ability to parse a topic and decide which servlet to associate with.

Written in the end: Welcome message discussion, welcome attention, Continuous Update!

Java in the common spring interview problem TOP50

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.