27 Spring high-frequency face questions, you can answer a few?

1. What is the Spring framework, what are the main module Spring framework
Spring Framework is to provide a comprehensive, broad-based support for the Java platform for Java application development. Spring to help developers solve the problem of the development of fundamental, so that developers can focus on application development. Spring Framework itself is well-built according to the design mode, which allows us to confidently integrate the Spring Framework development environment, do not have to worry about how Spring works in the background.
2, using the Spring framework which can bring benefits
Here are some of the major benefits of using the Spring Framework provides.
(1) Dependency Injection (DI) and configured such that the dependency JavaBean properties files at a glance.
(2) Compared with the EJB container, IoC containers tend to be more lightweight. As a result the use of IoC container to develop and publish the application in the case of limited memory and CPU resources becomes very favorable.
(3) Spring no closed doors, Spring advantage of existing technology, such as ORM framework, the logging framework, J2EE, Quartz and JDK Timer, views, and other techniques.
(4) Spring Framework is organized in the form of modules. By the packet number and type module can be seen, it belongs to the developer only needs to selection module.
(5) to be tested with a Spring application development is very simple, because the test environment-related code have included in the framework. More simply, using POJO class JavaBean form, it can be easily used to write test data dependency injection.
Web MVC framework (6) Spring Web framework is a well-designed to provide developers, not popular alternative to the mainstream framework in addition to a Web framework (such as Struts) and over-designed in the choice of Web framework. |
(7) Spring provides a convenient transaction management interface for small local transaction processing (such as in a single DB environment) and complex common transaction processing (such as the use of complex DB JTA environment).
3, what is inverted control (the IoC), what is the dependency injection
(1) is applied to the inversion control field of software engineering, is fitted at runtime object coupled to a programming technique bound objects, objects of the coupling relationship between at compile time is usually unknown. In traditional programming, the business logic flow is already set by the application of a good object association to decide. In the case where the inversion of control, business logic flow graph is determined by the object, which is responsible for assembling object graph instantiation, this implementation can also define relationships between abstract objects . Binding is through the process of "dependency injection" to achieve. (2) is an inversion of control applications to impart more control target component for the purpose of design paradigms, and play an effective role in the practical work. (3) Dependency injection is required during compilation function is not yet known what is the case from the classes of the other object is dependent object instantiation function mode. This requires a mechanism to activate the respective components to provide a particular function, the base control dependency injection is reversed. Otherwise, if the components are not in the case of the control framework, the framework and how to know which components you want to create it?
4, in which Java dependency injection mode
(1) constructor injection. (2) Setter injection method. (3) interface injection.
5, BeanFactory and ApplicationContext What is the difference
BeanFactory factory class can be understood as comprising a set of Bean. Bean BeanFactory contains the definition of the order corresponding to the received client requests instantiation Bean. BeanFactory also generate cooperative relationships between classes when the object is instantiated. This will liberate itself from Bean Bean client's configuration. Bean BeanFactory also includes control of the life cycle, initialization method is called (Initialization Method) and methods of destruction (Destruction Method) client. On the surface, as the ApplicationContext BeanFactory Bean defined as having a set relationship Bean and Bean distribution function upon request. But ApplicationContext On this basis, also provides other functions.
(1) provides support for international text messages.
(2) a unified way to read resource files.
(3) Bean of events registered in the listener.
The following are three of the more common ApplicationContext implementations.
(1) ClassPathXmlApplicationContext: ClassPath read from the context XML configuration file, and generates context definition. Application Context taken from the program environment variable.
ApplicationContext context = new ClassPathXmlApplicationContext(“application.xml”);
(2) FileSystemXmlApplicationContext: reading a file system context XML configuration file.
ApplicationContext context = new FileSystemXmlApplicationContext(“application.xml”);
(3) XmlWebApplicationContext: read the context of the XML file for the Web application.
6, Spring provides several ways to configure the metadata set
Spring provides the following three ways to configure metadata set:
(1) XML-based configuration. (2) annotation-based configuration. (3) Java-based configuration.
7, how to use Spring XML configuration to configure
the Spring framework, dependency and service needs special configuration file to achieve, usually in XML format configuration files. The format of these configuration files using a common template, Bean defined by a series of configuration options and specialized application components. The main purpose is to make Spring XML configuration Spring All components can be used as an XML file to configure. This means that other Spring configuration types (such as declarations or configuration-based Java Class configuration mode) does not appear. Spring XML configuration is to use a series of XML tags supported by the Spring namespace to achieve. Spring main namespace have context, beans, jdbc, tx, aop, mvc and aso. E.g:

<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 configured with only DispatcherServlet, the simplest configuration will be able to meet the requirements of a component application runtime configuration.

<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>
</web-app>

8, Spring provides a configuration which forms br /> Spring support for Java configuration is made @Configuration annotations and notes @Bean achieved. @Bean annotated by the method will instantiate, configure and initialize a new object that will be the Spring IoC container to manage. @Bean statement and the role of similar elements. @Configuration be annotated class, it said the main purpose of this class is defined resources as a Bean. @Configuration class is declared by the embedded dependencies Bean calls the same method to set the internal @bean class.
The simplest class @Configuration statement please refer to the following code:

@Configuration
publicclass AppConfig{

 @Bean
 public MyService myService() {
 return new MyServiceImpl();
    }

}

And above @Beans profile the same XML configuration file as follows:

<beans>
 <bean id="myService" class="com.gupaoedu.services.MyServiceImpl"/>
</beans>

Examples of the above-described configuration of the embodiment is as follows:

publicstaticvoid main(String[] args) {
 ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
 MyService myService = ctx.getBean(MyService.class);
    myService.doStuff();
} 
要使用组件扫描,仅需用@Configuration进行注解即可:
@Configuration
@ComponentScan(basePackages = "com.gupaoedu")
publicclass AppConfig  {

}

In the example above, com.gupaoedu package will first be scanned, and then look @Component class is declared in the container and find these classes will be registered in accordance with the Spring Bean definition.
If you want to choose the above configuration in Web application development, we need to use AnnotationConfigWebApplicationContext class to read a configuration file that can be used to configure the Servlet listener ContrextLoaderListener Spring or Spring MVC's DispatcherServlet.
E.g:

<web-app>
 <context-param>
 <param-name>contextClass</param-name>
 <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
 </context-param>

 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>com.gupaoedu.AppConfig</param-value>
 </context-param>

 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextClass</param-name>
 <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
 </init-param>

 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>com.gupaoedu.web.MVCConfig</param-value>
 </init-param>
 </servlet>

 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/web/*</url-pattern>
 </servlet-mapping>
</web-app>

9, how to configure Spring with annotations manner
Spring after the 2.5 version began to support the same general approach configuration dependency injection. Annotations can be used instead of XML manner described embodiment Bean, Bean may be transferred to the internal components of the class described, just in the Class, to the method of using annotations or field declaration. Annotation will be injected into the container processed before XML injection, the latter overrides the former deals with the results for the same property.
Notes assembled in Spring is off by default, need to be configured to use the assembly model based annotation in Spring file. If the way you want to use annotations in your application, please refer to the following configuration:

<beans>
 <context:annotation-config/>
</beans>

After the configuration, it can be used as annotations to the attributes, methods and constructors of the automatic assembly variable in Spring.
Here are some of the more important types of annotations.
(1) @Required: This comment applies setter.
(2) @Autowired: the annotation applies to a setter, a non-setter, constructor and variables.
(3) @Qualifier: @Autowired annotation and the annotation with the use of a particular Bean disambiguation automatic assembly.
(4) JSR-250 Annotations: Spring supports annotations based on JSR-250 annotations, ie @ Resource, @ PostConstruct and @PreDestroy.
10. Please explain Spring Bean lifecycle
Spring Bean's life cycle is simple and easy to understand. When a Bean instance is initialized, the following sequence of operations in order to reach the initialization state is available. Similarly, when a call is no longer required Bean related destructor operation, Bean and removed from the vessel. Spring Bean Factory is responsible for managing the lifecycle of Bean is created in the Spring container. Bean's life cycle consists of two groups composed callback method.
(1) callback method called after initialization.
(2) callback method invoked before destroying.
Spring provides the following four ways to manage Bean's life cycle events:
(1) InitializingBean and DisposableBean callback interface.
(2) Other Aware interfaces for specific behavior.
CustomInit (3) Bean configuration file () method and customDestroy () method.
br /> (4) @PostConstruct and @PreDestroy annotation mode.
Use customInit () and customDestroy () method Bean lifecycle management code sample as follows:

<beans>
 <bean id="demoBean" class="com.gupaoedu.task.DemoBean" init-Method="customInit" destroy-Method="customDestroy"></bean>
</beans>

11, the difference between the scope of what Spring Bean
Spring container Bean can be divided into five scope. All names are self-explanatory scope, but in order to avoid confusion, let us explain.
(1) singleton: This Bean scope is the default, this scope to ensure that no matter how many requests received, only one each container Bean instance, be maintained by a singleton Bean Factory's itself.
(2) prototype: prototype scope and singleton scope contrast, a request instance for each Bean.
(3) request: In each network request from the client request Bean scope create an instance, after the completion of the request, and will fail Bean garbage collected.
(4) Session: Scope and request similar to ensure that each has a Session Bean instance, after the Session expired, Bean will follow failure.
(5) global-session: global -session related and Portlet application. When the Portlet application deployment in a container, it contains a lot of Portlet. If you want all Portlet common global memory variable, then the global variables stored in the global-session needs to be stored in. Session scope global scope and effect are the same Servlet.
12. What is the Spring Inner Bean
in Spring, whenever, when Bean was only called a property, a sensible approach is to declare the Bean internal Bean. Bean injection may be implemented internal "properties" and injection "construction parameters" as used constructor manner setter. For example, in an application a Customer class references a Person class, we need to create an instance of the Person class, and then use within Customer.
**public class Customer {
private Person person;

}

public class Person {

private String name;

private String address;

private int age;

} **
internal Bean statement as follows:

<bean id="CustomerBean" class="com.gupaoedu.common.Customer">

 <property name="person">
 <bean class="com.gupaoedu.common.Person">
 <property name="name" value="lokesh"/>
 <property name="address" value="India"/>
 <property name="age" value="34"/>
 </bean>
 </property>

</bean>

13, Spring singleton Bean thread-safe is it
Spring does not perform any processing on the multi-thread single package embodiment Bean. Thread safety and concurrency issues regarding Singleton Bean developers need to be resolved. But in fact, most of the Spring Bean did not state variable (such as Serview class and the DAO class), in some way, Spring Bean is singleton thread safe. Bean if you have multiple states (such as View Model objects), it is necessary to ensure their own security thread.
The easiest solution is to polymorphic Bean scopes by the "singleton" is changed to "prototype".
14, please illustrate how to inject a set of Java in Spring
Spring provides the following four elements arranged collections of:
(. 1) <list> tag is used to assemble the list repeatable value.
(2) <set> tag is used to set the value of the assembly is not repeated.
(3) <map> tag values and keys used for injection, can be any type of key.
(4) <props> tag values and keys are implanted support string type pairs.
Let's look at a specific example:

<beans>

 <bean id="javaCollection" class="com.gupaoedu.JavaCollection">
 <property name="customList">
 <list>
 <value>INDIA</value>
 <value>Pakistan</value>
 <value>USA</value>
 <value>UK</value>
 </list>
 </property>

 <property name="customSet">
 <set>
 <value>INDIA</value>
 <value>Pakistan</value>
 <value>USA</value>
 <value>UK</value>
 </set>
 </property>

 <property name="customMap">
 <map>
 <entry key="1" value="INDIA"/>
 <entry key="2" value="Pakistan"/>
 <entry key="3" value="USA"/>
 <entry key="4" value="UK"/>
 </map>
 </property>

 <property name="customProperies">
 <props>
 <prop key="admin">[email protected]</prop>
 <prop key="support">[email protected]</prop>
 </props>
 </property>
 </bean>

</beans>

15, how to inject into the Spring Bean java.util.Properties
first method is to use the tag as shown in the following code:

<bean id="adminUser" class="com.gupaoedu.common.Customer">

 <property name="emails">
 <props>
 <prop key="admin">[email protected]</prop>
 <prop key="support">[email protected]</prop>
 </props>
 </property>

</bean>

It can also be "util:" namespace to create a Properties Bean Properties from the file, and then use the setter method injection Bean references.
16, please explain Spring Bean automatic assembly
in the Spring framework, Bean dependency set is a good mechanism in the configuration file, the container may also be automatically fitted Spring association between the relationship Bean. This means that Spring can be injected into the BeanFactory way to automatically get the dependencies between Bean. Automatic assembly may be provided on each Bean, it may be provided on a particular Bean.
The following XML configuration file shows how a Bean set to automatic assembly mode based on the name:
&lt;bean id="employeeDAO" class="com.gupaoedu.EmployeeDAOImpl" autowire="byName" /&gt;
br /> In addition to the automatic assembly mode Bean configuration file provided can also be used to automatically assemble @Autowired annotation specified Bean. Required before using @Autowired annotation configuration in accordance with the following Spring configuration file is:
&lt;context:annotation-config /&gt;
can also achieve the same effect by arranging AutowiredAnnotationBeanPostProcessor in the configuration file:
&lt;bean class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/&gt;

After configured can be used to label the @Autowired:

@Autowired
public EmployeeDAOImpl(EmployeeManager manager){
 this.manager=manager;
}

17, which is equipped with an automatic limitation of
automatic assembly has the following limitations.
• Rewrite: You still need to use <property> setting indicates dependence, which means always override the automatic assembly. • native data type: You can not simply attribute automatic assembly, as the original type, and the string class. • Blur features: automatic assembly is not always accurate custom assembly, so if possible, try to use the custom assembly.
18. Please explain the difference between various modes of automatic assembly
There are five automatic assembly mode in Spring, let us analyze one by one.
(1) no: This is the default setting in the Spring, which is provided at the automatic assembly is closed, the developer's own explicit dependencies Bean definitions provided by the label.
(2) byName: This mode can be set according to Bean name dependencies. When an attribute to an automatic assembling Bean, the container will automatically matching a query Bean name in the configuration file according to the Bean. If you found this property on the assembly, if not found on the error.
(3) byType: This mode may Bean dependency according to the type of setting. When an attribute to an automatic assembling Bean, the container automatically queries in a matching Bean profile according to the type of Bean. If you found this property on the assembly, if not found on the error.
(4) constructor: and byType mode, but only for Bean and constructors have the same type of argument, if consistent with the type of Bean constructor parameter is not found in the container, it will throw an exception.
br /> (5) autodetect: Automatic detection mode using the constructor byType automatic assembly or automated assembly. Will first try to find the appropriate constructor arguments, if that is found with automatic assembly constructor, if not found in the constructor or a constructor inside Bean constructor with no arguments, containers byType mode automatically selected.
** `19,` Please give an example to explain @Required comment **
In the product-level applications, IoC containers may declare hundreds of thousands Bean, with complex dependencies between Bean and Bean. One of the short board setter annotation method is to verify that all properties annotated is a very difficult operation. We can solve this problem by setting the "dependency-check".
In the life cycle of the application, you may not be willing to take the time to verify whether all the attributes Bean as the context file is configured correctly, or if you would rather verify whether a particular attribute of a Bean is set correctly. That the use of "dependency-check" attribute can not be a good solution to this problem, in this case requires the use of @Required comment.
Setter available in the following manner to indicate the Bean:
public class EmployeeFactoryBean the extends AbstractFactoryBean <Object> {

private String designation;

public String getDesignation() {
return designation;
}

@Required
public void setDesignation(String designation) {
this.designation = designation;
}

}
The RequiredAnnotationBeanPostProcessor is in Spring postprocessor was used to verify @Required Bean properties are annotated set correctly. Before using RequiredAnnotationBeanPostProcesso verify Bean property to be registered in the IoC container:
&lt;bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" /&gt;
br /> However, if the property is not annotated with @Required, post-processor will throw a BeanInitializationException exception.
20. Please provide examples of @Qualifier notes
br /> @ Qualifier annotation means can be automatically assembled on the field labeled Bean. @Qualifier annotation can be used to cancel the Spring Bean can not cancel the application.
21, constructor injection and setter injection What is the difference
Please note the following significant differences:
(1) set the value of the injection support most of dependency injection, the method only if we need to inject int, string and a long type variable, do not use the set value injection. For primitive types, if not injected, the default value may be set as the basic type. Constructor injection does not support most of dependency injection, because you must pass the correct configuration parameters when calling the constructor, otherwise it will error.
(2) does not rewrite the value set value of the injected constructor. If we use the constructor injection and setter injection for the same variable, then the constructor will not cover the value of the set value of the injection. Obviously, because the constructor is called only when the object is created.
(3) using the setter injection was also unable to guarantee whether a dependent has been injected, that is, when the object dependencies are likely to be incomplete. In another case, constructor dependency injection is not allowed to generate incomplete object.
(4) when the set value of the injected if the object A and the object B interdependent, create the object A the Spring ObjectCurrentlyInCreationException exception will be thrown because the object A can not be created before the object B is created, and vice versa. Spring with a set value of the injected solve the problem of circular dependencies, because setter object is to be called before the object is created.
22, Spring What are the different types of events
Spring ApplicationContext provides support and event code listener function.
We can create Bean to monitor events in the ApplicationContext released. For ApplicationEvent class and event handling in the ApplicationContext interface, if a ApplicationListener Bean implements the interface, when after a ApplicationEvent was released, Bean will automatically be notified.

public class AllApplicationEventListener implements ApplicationListener<ApplicationEvent> {

 @Override
 public void onApplicationEvent(ApplicationEvent applicationEvent) {
 //process event
    }

}

Spring provides the following five standard events.
(1) context update event (ContextRefreshedEvent): This event will be initialized or publish updates ApplicationContext. Can also refresh the call ConfigurableApplicationContext interface is triggered () method.
(2) the context of the start event (ContextStartedEvent): This event is triggered when a container calls ConfigurableApplicationContext the Start () method is started or restarted container.
(3) the context of stop event (ContextStoppedEvent): This event is triggered when a container calls ConfigurableApplicationContext the Stop () method to stop the vessel.
(4) the context of the closing event (ContextClosedEvent): This event is triggered when the ApplicationContext is closed. When the container is closed, all singleton Bean their management have been destroyed.
(5) request processing events (RequestHandledEvent): In Web applications, the event is triggered when the end of an HTTP request (Request).
In addition to the event described above, you can also customize the event by extending ApplicationEvent categories:

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, also we need to create a listener:

public class CustomEventListener implements ApplicationListener<CustomApplicationEvent> {

 @Override
 public void onApplicationEvent(CustomApplicationEvent applicationEvent) {

    }

}

After to publish custom event by publishEvent () method ApplicationContext interface:

CustomApplicationEvent customEvent=new CustomApplicationEvent(applicationContext, "Test message");
applicationContext.publishEvent(customEvent

23, FileSystemResource and ClassPathResource What is the difference
in FileSystemResource the need to give a relative path or absolute path spring-config.xml file in the project. It will automatically search for the configuration file in ClassPath in ClassPathResource in Spring, so take ClassPathResource files in the ClassPath.
If you save the next spring-config.xml in the src directory, you can just give the name of the configuration file, src is because the default path.
In short, ClassPathResource reads the configuration file in the environment variable, FileSystemResource reads the configuration file in the configuration file.
24, Spring used in the design mode which
Spring uses a lot of design patterns, Here are some of the more typical design patterns.
(1) proxy mode: more than is used in the AOP and remoting.
(2) Singleton: Spring defined in the default configuration file Bean singleton.
(3) Template Mode: Repeat the code to solve problems, such as RestTemplate, JmsTemplate, JpaTemplate.
(4) designating mode: Spring DispatcherServlet provided to the request for distribution.
(5) the factory mode: BeanFactory is used to create an object instance, and throughout the BeanFactory ApplicationContext interface.
(6) Agent Mode: Proxy mode AOP thought underlying implementation technology, Spring JDK Proxy and used CGLib libraries.
25, how to more effectively use JDBC in Spring
Spring JDBC can make use of the cost of resource management and error handling is reduced. Developers only need to access data from the database queries through statements and statements. Spring template classes through more effective use of JDBC, also known as JdbcTemplate.
26, please explain in Spring IoC container
Spring org.springframework.beans package and the package formed the basis org.springframework.context Spring IoC container.
BeanFactory interface provides an advanced configuration mechanism, making the configuration objects of any kind are possible. ApplicationContex interface BeanFactory (a sub-interface) has been extended, additional functionality was added on the basis of BeanFactory, such as easier integration with Spring AOP, also provides a mechanism for handling Message Resource's (for international), as well as events specially configured dissemination and application layer, such as WebApplicationContext application for the Web.
27, may be injected in Spring null or empty string it
completely.

I remember one article like Chan Chan, thanks for the support!

Guess you like

Origin blog.51cto.com/14442094/2423148