Spring interviews with the underlying principles of the question, do you really understand spring?

Source: Internet
Author: User
Tags aop error handling http 2

1. What is the Spring framework? What are the main modules of the Spring framework?
The Spring framework is a Java platform that provides a comprehensive, broad base of support for the development of Java applications. Spring
Helps developers solve the foundational issues in development, allowing developers to focus on application development. Spring Box
The frame itself is carefully crafted in accordance with the design pattern, which allows us to integrate the Spring framework with ease in the development environment without
Worry about how Spring works in the background.
The Spring framework has so far integrated more than 20 modules. These modules are mainly divided into the core containers as shown, data access/
Integration, Web, AOP (aspect-oriented programming), tools, messaging, and test modules.

2. What are the benefits of using the Spring framework?
The following are some of the key benefits of using the Spring framework:
1, the Dependency Injection (DI) method makes the dependencies in the constructor and JavaBean properties file a
target.
2, compared to EJB containers, IOC containers tend to be lightweight. This makes it advantageous for the IOC container to develop and publish applications in the context of limited memory and CPU
resources.
3, Spring is not behind closed doors, spring leverages existing technologies such as ORM framework, logging framework, Java EE,
Quartz and JDK Timer, and other view technologies.
4, the Spring framework is organized in the form of modules. By the number of packages and classes you can see the module they belong to, the developer
just need to choose the module they need.
5, it's easy to test a Spring-developed application because the test-related environment code is already in the box
frame. More simply, using the JavaBean form of the POJO class, it is convenient to use dependency injection to write the test
test data. The
6, Spring Web Framework is also a well-designed web MVC framework that provides developers with a powerful option beyond mainstream frameworks such as Struts, over-engineered, and non-popular web frameworks for Web framework selection
.
7, Spring provides a convenient transaction management interface for small, local transactions (such as in a single DB environment
) and complex common transactions (such as a complex DB environment leveraging JTA).

3. What is inversion of control (IOC)? What is dependency injection?
1, control inversion is applied in the field of software engineering, at run time by the Assembler object to bind the coupling object of a programming technique
Coincidentally, the coupling relationship between objects is usually unknown at compile time. In the traditional way of programming, the process of business logic is determined by the application
The program is already determined by the objects that have been set up in relation to the relationship. In the case of control inversion, the flow of business logic is
is determined by the object graph, which is instantiated by the assembler, which also enables the object
An abstraction of the definition of an association relationship. The process of binding is implemented through "dependency injection".
2. Control inversion is a design paradigm that gives more control to the target components in the application, and in our actual work
Play an effective role in the
3. Dependency injection is the case where the required functionality is not known in the compile phase, the work that other objects depend on
The mode in which the object can be instantiated. This requires a mechanism to activate the corresponding component to provide specific functionality, so dependency injection
Is the basis of control inversion. Otherwise, how does the framework know which component to create if the component is not controlled by the framework?
4, in Java still injected with the following three ways to achieve:
1. Constructor injection
2.Setter Method Injection
3. Interface Injection

4. Please explain the IOC in the Spring framework.
The Org.springframework.beans package and the Org.springframework.context package in Spring form the
The base of the Spring framework IOC container.
The Beanfactory interface provides an advanced configuration mechanism that makes it possible to configure any type of object.
The Applicationcontex interface extends the beanfactory (which is a sub-interface) to the base of the Beanfactory
Additional functionality, such as easier integration with Spring's AOP, and the handling of message resource
(for internationalization), event propagation, and special configuration of the application layer, such as those for WEB applications
Webapplicationcontext.

What is the difference between

5, beanfactory, and ApplicationContext? The
Beanfactory can be understood as a factory class that contains a bean collection. Beanfactory contains the definition of a bean that, in
, instantiates the corresponding bean when it receives a client request. The
Beanfactory can also generate relationships between collaboration classes when instantiating an object. This frees the bean itself from the configuration of the Bean client
. Beanfactory also contains the bean lifecycle control, invoking the client's initialization method
(initialization methods) and the Destroy method (destruction methods).
on the surface, application context, like Bean factory, has the bean definition, bean affinity
setting, which distributes the bean's functionality on request. However, the application context also provides other features on this basis.
1. Provides a text message that supports internationalization
2. Unified resource file Read Method
3. Events for beans registered with listeners
The following are three more common implementations of ApplicationContext:
1, Classpathxmlapplicationcontext: Reads the context from the Classpath XML configuration file and generates a
context definition. The application context is obtained from the program environment variable.
ApplicationContext context = new Classpathxmlapplicationcontext ("Application.xml");
2, Filesystemxmlapplicationcontext: The context is read by the XML configuration file in the file system.
ApplicationContext context = new Filesystemxmlapplicationcontext ("Application.xml");
3, Xmlwebapplicationcontext: The context is read by the Web app's XML file.

6, Spring provides several configuration methods to set up metadata?
There are three ways to configure Spring to application development:
1. XML-based configuration
2. Annotation-based configuration
3. Java-based configuration

7. How do I configure Spring using the XML configuration?
In the Spring framework, dependencies and services need to be implemented in a dedicated configuration file, which I commonly use in XML format configuration files.
The format of these configuration files is usually preceded by a series of bean definitions and specialized application configuration options.
The primary purpose of the Springxml configuration is to enable all spring components to be configured in the form of an XML file.
This means that no other Spring configuration types are present (such as declarative or Java Class-based configuration)
The XML configuration for spring is implemented using a series of XML tags that are supported by the spring namespace.
Spring has the following key namespaces: Context, beans, JDBC, TX, AOP, MVC, and ASO.

<beans>

The following Web. XML is only configured with Dispatcherservlet, the simplest configuration to meet the requirements of the application configuration runtime components. archetype Created Web application spring Org.springframework.web.servlet.Dispa Tcherservlet 1 spring / 8. How do I configure Spring in a Java configuration-based way? Spring's support for Java configuration is implemented by @configuration annotations and @bean annotations. The method annotated by @bean will instantiate, configure, and initialize a new object, which will be managed by the Spring IOC container. @Bean declarations have a similar effect as elements. The class that is annotated by @configuration indicates that the primary purpose of this class is to serve as a resource defined by the bean. Classes declared by @configuration can set the dependency of an embedded bean by calling the @bean method inside the same class. The simplest @configuration declaration class refer to the following code: @Configurationpublic class appconfig{@Beanpublic myservice MyService () {return new Myserviceimpl ();}} The same XML configuration file for the above @beans configuration file is as follows: The above configuration is instantiated as follows: Using the Annotationconfigapplicationcontext class to instantiate public static void main (string[] args) {ApplicationContext CTX = new Annotationconfigapplicationcontext (appconfig.class); MyService MyService = Ctx.getbean (Myservice.class); Myservice.dostuff ();} To use component building scans, only @configuration annotations are required: @Configuration @componentscan (basepackages = "com.gupaoedu") public class AppConfig {} In the example above, the com.gupaoedu package is first swept to the container and then the @component declared class is found, and the classes are registered according to the sring bean definition. More interview information in Group 766529531 free access (jvm/concurrent programming/Distributed/microservices/interview troubleshooting can be obtained for free in the group) if you want to use the above configuration in your Web application development, you need to Annotat Ionconfigwebapplicationcontext class to read a configuration file that can be used to configure spring's servlet listener Contrextloaderlistener or spring MVC's Dispatcherservlet. contextclass org.springframework.web.context.support.AnnotationConfigWebApplicationContext contextconfiglocation com.gupaoedu.AppConfig Org.springframework.web.context.ContextLoaderListener Dispatcher Org.springframework.web.servlet.DispatcherServlet contextclass org.springframework.web.context.support.AnnotationConfigWebApplicationContext contextconfiglocation com.gupaoedu.web.MVCConfig Dispatcher /web/* 9. How to configure Spring with annotations? Spring began to support annotation-based configuration of dependency injection after version 2.5. You can use annotations to replace the bean description in XML mode, and you can transfer the bean description to the inside of the component class by using annotations on the relevant class, method, or field declaration only. The annotation injection will be processed by the container before the XML is injected, so the latter will overwrite the result of the previous processing of the same attribute. The annotation assembly is closed by default in Spring. So you need to configure it in the Spring file to use annotation-based assembly mode. If you want to use the annotation method in your application, please refer to the following configuration. After the label configuration is complete, you can automatically assemble the variables in Spring, in the form of annotations, to properties, methods, and construction methods. Here are some of the more important types of annotations: [email protected]: This annotation is applied to the set value method. [Email protected]: This annotation applies to value-setting methods, non-setpoint methods, construction methods, and variables. [Email protected]: This annotation is used in conjunction with @autowired annotations to eliminate ambiguity in the automatic assembly of a particular bean. 4.JSR-250 Annotations:spring supports the following annotations based on JSR-250 annotations, @Resource, @PostConstruct, and @PreDestroy. 10. Please explain the Spring Bean's life cycle? The life cycle of Spring beans is easy to understand. When a bean instance is initialized, it is necessary to perform a series of initialization operations to achieve the available state. Similarly, when a bean is not being invoked, it needs to be related to the destructor and removed from the bean container. Spring Bean Factory is responsible for managing the life cycle of the bean that is created in the spring container. The life cycle of a Bean consists of two sets of callback (call-back) methods. 1. Callback method that is called after initialization. 2. Destroy the callback method that was called before. The Spring framework provides the following four ways to manage Bean lifecycle events: 1, Initializingbean and Disposablebean callback interface 2, other Aware interface 3 for special behavior, Custom init in the bean configuration file ( ) method and Destroy () method 4, @PostConstruct, and @predestroy annotations use the Custominit () and Customdestroy () methods to manage the bean life Cycle code sample as follows: 11. What is the difference between Spring Bean scopes? Beans in a Spring container can be divided into 5 ranges. The names of all scopes are self-explanatory, but to avoid confusion, let us explain: 1.singleton: This bean range is the default, which ensures that no matter how many requests are received, there is only one instance of the bean in each container, and the singleton pattern is factory by the bean themselves to maintain. 2.prototype: Prototype range in contrast to a singleton range, provide an instance for each bean request. 3.request: Within the request bean range, each network request from the client creates an instance, and after the request is completed, the bean is invalidated and reclaimed by the garbage collector. 4.Session: Similar to the request scope, ensure that there is an instance of the bean in each session, and the bean will expire after the session expires. More interview information is available for free in Group 766529531 (jvm/concurrent programming/Distributed/microservices/etc. interview video learning materials can be obtained for free) 5.global-session:global-session and Portlet application related. When your app is deployed to work in a portlet container, it contains many portlets. If you want to declare that all portlets share a global storage variable, then this global variable needs to be stored in global-session. The global scope has the same effect as the session scope in the Servlet. 12. What is Spring inner beans? In the Spring framework, whenever a bean is used, only one property is called. It is wise to declare this bean as an internal bean. Internal beans can be implemented using setter injection "properties" and construction methods to inject "construct parameters". For example, in our application, a customer class refers to a person class, and what we want to do is create an instance of the person and then use it inside the customer. public class Customer{private Person person;//setters and Getters}public class Person{private string Name;private string A ddress;private int age;//setters and Getters} internal beans are declared as follows: 13. Is the singleton Beans in the Spring framework thread-safe? The Spring framework does not have any multithreaded encapsulation of singleton beans. Thread safety and concurrency issues for singleton beans need to be done by developers themselves. In fact, most spring beans do not have a mutable state (such as the Serview class and the DAO Class), so spring's singleton beans are, to some extent, thread-safe. If your bean has multiple states (such as the View Model object), you will need to ensure thread safety yourself. The most obvious solution is to change the scope of the polymorphic bean from "Singleton" to "prototype". 14. Please illustrate how to inject a Java collection into Spring? Spring provides configuration elements for the following four collection classes: 1: This label is used to assemble a repeatable list value. 2: The label is used to assemble no duplicate set values. 3: The label can be used to inject keys and values can be any type of key-value pairs. 4: The tag supports both the injected key and the value are the key value pairs of the string type. Here's a look at the specific examples: !--java.util.List--> list> INDIA Pakistan USA U K !--java.util.Set--> INDIA Pakistan USA UK !--java.util.Map--> !--java.util.Prop Erties--> [email protected] [email protected] 15. How do I inject java.util.Properties into the Spring Bean? The first method is to use the label as shown in the following code: [email protected] [email protected] You can also use the "Util:" namespace to create a Propertiesbean from the properties file and then inject the bean reference with the setter method. 16. Please explain the automatic assembly of Spring Bean. In the spring framework, it is a good mechanism to set the bean dependencies in the configuration file, and the spring container can also automatically assemble the association relationships between the partnership beans. This means that Spring can automatically take care of the dependencies between beans by injecting it into the bean Factory. The automatic assembly can be set on each bean or on a specific bean. The following XML configuration file shows how to set up a bean to be automatically assembled by name: In addition to the automatic assembly mode provided in the bean configuration file, you can also use @autowired annotations to automatically assemble the specified bean. Before using @autowired annotations, you need to configure the Spring configuration file to use it as follows. You can also achieve the same effect by configuring Autowiredannotationbeanpostprocessor in the configuration file. ? 1 after configuration, you can use @autowired to mark it. @Autowiredpublic Employeedaoimpl (Employeemanager manager) {This.manager = Manager;} 17, please explain the various automatic assembly mode differences? There are 5 kinds of automatic assembly in the Spring framework, let's analyze it one by one. 1.no: This is the default setting for the Spring framework, where automatic assembly is turned off, and developers need to explicitly set dependencies in the bean definition by themselves. 2.byName: This option sets the dependency relationship based on the bean name. When an attribute is automatically assembled into a bean, the container automatically queries a matching bean in the configuration file based on the name of the bean. If found, assemble this property, and if not found, an error. 3.byType: This option allows you to set dependencies based on the bean type. When an attribute is automatically assembled into a bean, the container automatically queries a matching bean in the configuration file based on the type of the bean. If found, assemble this property, and if not found, an error. 4.constructor: The automatic assembly of the builder is similar to the Bytype mode, but only applies to beans with the same parameters as the constructor, and throws an exception if no bean is found in the container that matches the constructor parameter type. 5.autodetect: This mode automatic detection uses the constructor automatic assembly or Bytype automatic assembly. First of all, we will try to find the appropriate constructor with parameters, if it is found is automatically assembled with the constructor, if the inside of the bean does not find the corresponding constructor or a parameterless constructor, the container will automatically select the BYTPE automatic assembly mode. 18, how to open the automatic annotation-based assembly? To use the @Autowired, you need to register autowiredannotationbeanpostprocessor, which can be implemented in the following two ways: 1, introduced under the introduction of the configuration file 2. Introducing autowiredannotationbeanpostprocessor directly into the bean configuration file 19. What are the limitations of automatic assembly? Automatic assembly has the following limitations: rewrite: You still need to use the and < property> settings to indicate dependencies, which means always rewriting automatic assembly. Native data type: You cannot automatically assemble simple properties, such as native types, strings, and classes. Blur Characteristics: Automatic assembly is always not custom assembled precisely, so if possible use custom assembly. 20. Can I inject null or an empty string in Spring? It's perfectly possible. 21. Please explain @required Annotation for example. In a product-level application, the IOC container might declare hundreds of thousands of, and the Bean,bean has a complex dependency relationship with the bean. One of the short boards that set the value annotation method is that it is a very difficult operation to verify that all properties are annotated. You can fix this problem by setting "Dependency-check" in. In the life cycle of your application, you may not be willing to spend time verifying that all bean properties are properly configured according to the context file. Or you would rather verify that a particular property of a bean is set correctly. Even using the "Dependency-check" attribute does not solve this problem very well, in which case you need to use the @required annotation. You need to use the following method to indicate the value of the bean's setting. public class Employeefactorybean extends Abstractfactorybean{private string Designation;public string Getdesignation () {return designation;} @Requiredpublic void Setdesignation (String designation) {this.designation = designation;}} Requiredannotationbeanpostprocessor is the post-processing in Spring to verify that the bean properties of the @required annotations are set correctly. Before you use Requiredannotationbeanpostprocesso to validate bean properties, you first register it in the IOC container: However, if no attribute is annotated with @Required, the post processor throws a Beaninitializationexception exception. 22. Please explain @autowired annotations for example. @Autowired annotations provide more granular control over when and where automated assembly is implemented. @Autowired annotations can be used to automatically assemble bean properties, a parameter, or a method with any name or with multiple parameters, like @required annotations and constructors, on the bean's set value method. For example, you can use @autowired annotations on the SetPoint method to override the elements in the configuration file. When the Spring container finds the @autowired annotation on the setter method, it attempts to assemble it automatically with Bytype. Of course we can also use @autowired annotations on construction methods. The construction method with the @autowired annotation means that it will be automatically assembled when a bean is created, even if the element is used in the configuration file. public class TextEditor {private Spellchecker spellchecker; @Autowiredpublic texteditor (Spellchecker spellchecker) { System.out.println ("Inside TextEditor constructor."); This.spellchecker = spellchecker;} public void SpellCheck () {spellchecker.checkspelling ();}} The following are the configurations that have no construction parameters: 23, please illustrate @qualifier annotation? @Qualifier annotations mean that they can be automatically assembled on the fields of the labeled Bean. Qualifier annotations can be used to cancel a bean application that Spring cannot cancel. The following example automatically assembles the value of person in the Customer's Person property. public class customer{@Autowiredprivate the person person;} Below we want to configure the person class in the configuration file. Does Spring know which person bean to assemble automatically? No, but when you run the above example, the following exception is thrown: caused by:org.springframework.beans.factory.NoSuchBeanDefinitionException:No unique bean of type [Com.gupaoedu.common.Person] is defined:expected single matching beans but found 2: [PersonA, personb] to solve the above problem, you need to use @Quanlifier annotations to tell the Spring container which Bean:public class customer{to assemble @Autowired @qualifier ("PersonA") private person person;} 24. What is the difference between the construction method injection and the SetPoint injection? Please note the following notable differences: 1. The value injection method supports most of the dependency injection, and if we only need to inject variables of int, string, and long, we do not inject it with a value-setting method. For basic types, you can set a default value for the base type if we don't inject it. Most of the dependency injection is not supported in the constructor method injection because the correct construction parameters must be passed in the calling constructor, otherwise the error is incorrect. 2. Set value injection does not override the value of the constructed method. If we use both the constructor injection and the set method injection for the same variable, the constructor will not overwrite the value injected by the set value method. Obviously, because the construction method is called when the object is created. 3. When using setpoint injection, it may not be possible to ensure that a dependency has been injected, which means that the dependency of the object may be incomplete. In another case, the constructor injection does not allow the generation of an object with incomplete dependencies. 4. If object A and object B are dependent on each other when setting value injection, Spring throws an Sobjectcurrentlyincreationexception exception when creating object A, because before the B object is created A object cannot be created, and vice versa. So Spring solves the problem of cyclic dependency with the method of setting the value, because the object's value method is called before the object is created. More interview information available in Group 766529531 free (jvm/concurrent programming/Distributed/microservices/interview troubleshooting can be obtained for free in the group) 25. What are the differences in the Spring framework?Type of event? Spring's ApplicationContext provides the ability to support events and listeners in code. We can create beans to listen for events published in ApplicationContext. The Applicationevent class and the events handled in the ApplicationContext interface, if a bean implements the Applicationlistener interface, when a applicationevent is released, the bean will be notified automatically. public class Allapplicationeventlistener implements Applicationlistener {@Overridepublic void onapplicationevent (Applicationevent applicationevent) {//process Event}} Spring provides the following 5 standard events: 1. Context Update event (contextrefreshedevent): This event is published when ApplicationContext is initialized or updated. It can also be triggered when the refresh () method in the Configurableapplicationcontext interface is called. 2. Context Start Event (contextstartedevent): This event is triggered when the container invokes Configurableapplicationcontext's start () method to begin/Restart the container. 3. Context stop event (contextstoppedevent): This event is triggered when the container calls the Stop () method of Configurableapplicationcontext. 4. Context Shutdown Event (contextclosedevent): This event is triggered when ApplicationContext is closed. When a container is closed, all the singleton beans it manages are destroyed. 5. Request Processing Event (Requesthandledevent): In a Web app, the event is triggered when an HTTP request (request) ends. In addition to the events described above, you can develop custom events by extending the Applicationevent class. public class Customapplicationevent extends Applicationevent{public customapplicationevent (Object source, final String msg) {super (source); System.out.println ("Created a Custom event");}} To listen to this event, you also need to create a listener: public class Customeventlistener implements Applicationlistener {@Overridepublic void onapplicationevent (Customapplicationevent applicationevent) {//handle Event}} The Publishevent () method of the ApplicationContext interface to publish custom events. Customapplicationevent customevent = new Customapplicationevent (applicationcontext, "Test message"); Applicationcontext.publishevent (Customevent), 26, Filesystemresource and Classpathresource What is the difference? In Filesystemresource, you need to give the relative path or absolute path of the Spring-config.xml file in your project. In Classpathresource spring will automatically search for the configuration file in ClassPath, so put the Classpathresource file under ClassPath. If you save spring-config.xml in the src folder, just give the name of the configuration file, because the SRC folder is the default. In short, Classpathresource reads the configuration file in the environment variable and Filesystemresource reads the configuration file in the configuration file. 27. What design patterns are used in the Spring framework? A large number of design patterns are used in the Spring framework, and the following are the more representative: 1, Proxy mode-more used in AOP and remoting. 2. Singleton mode: The bean defined in the spring configuration file defaults to singleton mode. 3, Template mode: To solve the problem of code duplication. Like what. Resttemplate, Jmstemplate, Jpatemplate. 4. Delegation Mode: Spring provides dispatcherservlet to distribute the request. 5, Factory mode: Beanfactory used to create an instance of the object, running through the core concept of the Beanfactory/applicationcontext interface. 6, Agent mode: The bottom-level implementation technology of AOP thought, using JDK Proxy and CgLib class library in Spring. 28, in SHow do I use JDBC more effectively in the Pring framework? With the spring JDBC Framework, the cost of resource management and error handling can be mitigated. Developers only need to access data from the database through statements and queries statements. Using the template classes in the Spring framework makes it more efficient to use JDBC, the so-called JdbcTemplate. 29, Spring5 new features 1, dependent on JDK 8+ and Java ee7+ version 2, the first use of reactive programming Model 3, support the use of annotations for programming 4, new functional programming 5, support the use of REST breakpoints to execute reactive programming 6, support HTTP 2.07, new Kotlin and Spring WebFlux8, use LAMBDA expressions to register BEAN9, spring WEBMVC support the latest API10, use JUnit5 execution conditions and concurrency Test 11, perform integration test with Spring Webflux 12, Core container optimization

Spring interviews with the underlying principles of the question, do you really understand spring?

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.