The most comprehensive spring noodles questions and Answers

Source: Internet
Author: User

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. The spring framework itself is also crafted in accordance with the design pattern, which allows us to integrate the spring framework with peace of mind in the development environment without worrying 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 shown, data access/integration, WEB, AOP (aspect-oriented programming), tools, messages, and test modules.

More information: Spring Framework Tutorials.


2. What are the benefits of using the spring framework?

Here are some of the key benefits of using the Spring framework:

The Dependency injection (DI) method makes the dependencies in the constructor and JavaBean properties file at a glance.
Compared to EJB containers, IOC containers tend to be more lightweight. This makes it very advantageous for the IOC container to develop and publish applications in the context of limited memory and CPU resources.
Spring is not behind closed doors, and spring leverages existing technologies such as ORM Framework, logging framework, Java EE, quartz and jdk Timer, and other view technologies.
The spring framework is organized in the form of modules. By the number of packages and classes, you can see which modules they belong to, and developers just need to select the modules they need.
It is easy to test a spring-developed application because the test-related environment code is already in the framework. More simply, using the JavaBean form of the Pojo class, it is convenient to use dependency injection to write test data.
The 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 in the choice of web frameworks.
Spring provides a convenient transaction management interface for small-scale local object processing (e.g. in a single DB environment) and complex common-matter processing (such as the use of JTA's complex DB environment).

3. What is inversion of control (IOC)? What is dependency injection?

Control inversion is a programming technique used in the field of software engineering to bind objects of coupling at runtime by Assembler objects, and the coupling between objects is usually unknown at compile time. In traditional programming, the process of business logic is determined by the objects in the application that have already been set up to correlate the relationships. In the case of control inversion, the flow of business logic is determined by the object graph, which is instantiated by the assembler, which also abstracts the definition of the association between objects. The process of binding is implemented through "dependency injection".

Control inversion is a design paradigm that gives more control to the target components in the application, and plays an effective role in our practical work.

Dependency injection is the pattern of instantiating a feature object that other objects depend on in the case of a class that is not yet known to be the required functionality in the compilation phase. This requires a mechanism to activate the corresponding component to provide specific functionality, so dependency injection is the basis for control inversion. Otherwise, how does the framework know which component to create if the component is not controlled by the framework?

The following three implementations are still injected into Java:

Constructor injection
Setter Method Injection
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 basis 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) and adds additional functionality on top of beanfactory, such as easier integration with spring's AOP, and the processing of message Resource mechanisms (for internationalization), event propagation, and the application layer's special configuration, such as Webapplicationcontext for Web applications.

Org.springframework.beans.factory.BeanFactory is a concrete implementation of the spring IOC container to wrap and manage the various beans mentioned earlier. The Beanfactory interface is the core interface of the Spring IoC container.


5. What is the difference between beanfactory and ApplicationContext?

Beanfactory can be understood as a factory class that contains bean collections. Beanfactory contains the definition of a bean to instantiate the corresponding bean when a client request is received.

Beanfactory can also generate relationships between collaboration classes when instantiating an object. This frees the bean itself from the configuration of the Bean client. The beanfactory also contains the Bean lifecycle control, the invocation of the client's initialization method (initialization methods), and the Destruction method (destruction methods).

On the surface, application context, like Bean factory, has a bean definition, bean affinity setting, and the ability to distribute beans on request. However, the application context also provides other features on this basis.

Provides a text message that supports internationalization
Unified resource File Read mode
Events for beans that have been registered in the listener
Here are three more common ways to implement 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 ("Bean.xml"); 2, Filesystemxmlapplicationcontext : The context is read by the XML configuration file in the file system. ApplicationContext context = new Filesystemxmlapplicationcontext ("Bean.xml"); 3, Xmlwebapplicationcontext: The context is read by the Web app's XML file.


6, Spring has several configuration methods?

There are three ways to configure spring to application development:

XML-based configuration
Annotation-based configuration
Java-based configuration

7. How do I configure spring in a way that is based on 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 profiles is usually preceded by a <beans>, followed 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> <!--JSON Support---<bean name= "Viewresolver" class= "Org.springframework.web.servlet.view. Beannameviewresolver "/> <bean name=" jsontemplate "class=" Org.springframework.web.servlet.view.json.MappingJackson2JsonView "/> <bean id=" resttemplate "class=" Org.springframework.web.client.RestTemplate "/> </beans>


The following Web. XML is only configured with Dispatcherservlet, the simplest configuration to meet the requirements of the application configuration runtime components.

<web-app>  <display-name>archetype created web application</ display-name>   <servlet>        < servlet-name>spring</servlet-name>             <servlet-class>                 org.springframework.web.servlet.DispatcherServlet             </servlet-class>        < load-on-startup>1</load-on-startup>    </servlet>      <servlet-mapping>        <servlet-name>spring</ servlet-name>        <url-pattern>/</url-pattern>     </servlet-mapping>&nbsP;</web-app> 

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. The role of @Bean declaration is similar to the <bean/> element. 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 classes refer to the following code:


@Configurationpublic class appconfig{@Bean public MyService MyService () {return new Myserviceimpl (); }}

The same XML configuration file for the above @beans configuration file is as follows:


<beans> <bean id= "MyService" class= "Com.howtodoinjava.services.MyServiceImpl"/></beans>


The above configuration methods are instantiated as follows: Using the Annotationconfigapplicationcontext class for instantiation


public static void Main (string[] args) {ApplicationContext ctx = new Annotationconfigapplicationcontext (Appconfig.clas    s);    MyService MyService = Ctx.getbean (Myservice.class); Myservice.dostuff ();}

To use component building scans, only @configuration annotations are required:


@Configuration @componentscan (basepackages = "Com.howtodoinjava") public class AppConfig {...}


In the above example, the COM.ACME packet is first swept to the container and then the class that is declared by the @component is found, and the classes are registered according to the sring bean definition.

If you want to use the above configuration in your Web application development, you need to read the configuration file using the Annotationconfigwebapplicationcontext class. Can be used to configure spring's servlet listener Contrextloaderlistener or Spring MVC's dispatcherservlet.


<web-app>    <!-- configure contextloaderlistener to use  annotationconfigwebapplicationcontext        instead of  the default XmlWebApplicationContext -->    <context-param>         <param-name>contextClass</param-name>         <param-value>             org.springframework.web.context.support.AnnotationConfigWebApplicationContext         </param-value>    </context-param>      <!-- configuration locations must consist of one  or more comma- or space-delimited         fully-qualified  @Configuration classes. Fully-qualified packages may also be         specified for component-scanning -->    < context-param>        <param-name>contextconfiglocation</ Param-name>        <param-value>com.howtodoinjava.appconfig </param-value>    </context-param>     <!--  bootstrap the root application context as usual using  contextloaderlistener -->    <listener>         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>     </listener>     <!-- declare a spring  mvc dispatcherservlet as usual -->    <servlet>        < servlet-name>dispatcher</servlet-name>        < servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>         <!-- Configure DispatcherServlet to use  annotationconfigwebapplicationcontext             instead of the default xmlwebapplicationcontext -->         <init-param>             <param-name>contextClass</param-name>             <param-value>                 org.springframework.web.context.support.annotationconfigwebapplicationcontext             </param-value>        </init-param>         <!-- Again, config locations must  consist of one or more comma- or space-delimited             and fully-qualified  @Configuration  classes  -->        <init-param>             <param-name>contextConfigLocation</param-name>             <param-value> com.howtodoinjava.web.mvcconfig</param-value>        </ init-param>    </servlet>     <!-- map all requests for /app/* to the  dispatcher servlet -->    <servlet-mapping>         <servlet-name>dispatcher</servlet-name>         <url-pattern>/app/*</url-pattern>    </servlet-mapping ></web-app>

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.


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

After the <context:annotation-config/> 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:

@Required: The annotation is applied to the set value method.
@Autowired: This annotation applies to value-setting methods, non-setpoint methods, construction methods, and variables.
@Qualifier: This annotation is used in conjunction with @autowired annotations to eliminate ambiguity in the automatic assembly of a particular bean.
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.

callback method that is called after initialization.
The callback method that was called before the destroy.
The Spring framework provides the following four ways to manage bean lifecycle events:

Initializingbean and Disposablebean Callback interfaces
Other aware interfaces for special behavior
The custom init () method and the Destroy () method in the Bean configuration file
@PostConstruct and @predestroy annotation methods
The code sample that uses the Custominit () and Customdestroy () methods to manage the bean life cycle is as follows:


<beans> <bean id= "Demobean" class= "Com.howtodoinjava.task.DemoBean" init-method= "Custominit" Destro Y-method= "Customdestroy" ></bean></beans>


For more information, please refer to the Spring lifecycle Spring Bean life cycle.


11. What is the difference between the scope of the Spring bean?

Beans in a spring container can be divided into 5 ranges. The names of all scopes are self-explanatory, but to avoid confusion, let's explain:

Singleton: This bean range is the default, and this range 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 maintained by the Bean factory itself.
Prototype: The prototype range is the opposite of a singleton range, providing an instance for each bean request.
Request: an instance of each network request from the client is created within the scope of the requesting bean, and after the request is completed, the bean is invalidated and reclaimed by the garbage collector.
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.
Global-session:global-session is associated with portlet applications. 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.

For more information, please refer to: Spring Bean Scopes.


Original address: http://www.itmmd.com/201504/714.html
This article by Meng Meng's IT person to organize the release, reprint must indicate the source.

Copyright notice: I feel like I'm doing a good job. I hope you can move your mouse and keyboard for me to order a praise or give me a comment, under the Grateful!_____________________________________________________ __ Welcome reprint, in the hope that you reprint at the same time, add the original address, thank you with

Most complete spring-face questions and answers

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.