本人收集了一些在你们在面试时被常常问及的关于Spring的主要问题,这些问题有可能在你下次面试时就会被问到。对于本文中未说起的Spring其余模块,我会单独分享面试的问题和答案。html
欢迎你们向我推荐你在面试过程当中遇到关于Spring的问题。我会把你们推荐的问题添加到下面的Spring经常使用面试题清单中供你们参考。前端
Spring框架是一个为Java应用程序的开发提供了综合、普遍的基础性支持的Java平台。Spring帮助开发者解决了开发中基础性的问题,使得开发人员能够专一于应用程序的开发。Spring框架自己亦是按照设计模式精心打造,这使得咱们能够在开发环境中安心的集成Spring框架,没必要担忧Spring是如何在后台进行工做的。java
Spring框架至今已集成了20多个模块。这些模块主要被分以下图所示的核心容器、数据访问/集成,、Web、AOP(面向切面编程)、工具、消息和测试模块。web
更多信息:Spring 框架教程。面试
下面列举了一些使用Spring框架带来的主要好处:spring
控制反转是应用于软件工程领域中的,在运行时被装配器对象来绑定耦合对象的一种编程技巧,对象之间耦合关系在编译时一般是未知的。在传统的编程方式中,业务逻辑的流程是由应用程序中的早已被设定好关联关系的对象来决定的。在使用控制反转的状况下,业务逻辑的流程是由对象关系图来决定的,该对象关系图由装配器负责实例化,这种实现方式还能够将对象之间的关联关系的定义抽象化。而绑定的过程是经过“依赖注入”实现的。shell
控制反转是一种以给予应用程序中目标组件更多控制为目的设计范式,并在咱们的实际工做中起到了有效的做用。编程
依赖注入是在编译阶段还没有知所需的功能是来自哪一个的类的状况下,将其余对象所依赖的功能对象实例化的模式。这就须要一种机制用来激活相应的组件以提供特定的功能,因此依赖注入是控制反转的基础。不然若是在组件不受框架控制的状况下,框架又怎么知道要建立哪一个组件?json
在Java中依然注入有如下三种实现方式:设计模式
Spring中的 org.springframework.beans
包和 org.springframework.context
包构成了
Spring
框架
IoC
容器的基础。
BeanFactory 接口提供了一个先进的配置机制,使得任何类型的对象的配置成为可能。ApplicationContex
接口对
BeanFactory
(是一个子接口)进行了扩展,在BeanFactory的基础上添加了其余功能,好比与Spring的AOP更容易集成,也提供了处理message resource的机制(用于国际化)、事件传播以及应用层的特别配置,好比针对Web应用的WebApplicationContext。
org.springframework.beans.factory.BeanFactory
是Spring IoC容器的具体实现,用来包装和管理前面提到的各类bean。BeanFactory接口是Spring IoC 容器的核心接口。
BeanFactory 能够理解为含有bean集合的工厂类。BeanFactory 包含了种bean的定义,以便在接收到客户端请求时将对应的bean实例化。
BeanFactory还能在实例化对象的时生成协做类之间的关系。此举将bean自身与bean客户端的配置中解放出来。BeanFactory还包含了bean生命周期的控制,调用客户端的初始化方法(initialization methods)和销毁方法(destruction methods)。
从表面上看,application context如同bean factory同样具备bean定义、bean关联关系的设置,根据请求分发bean的功能。但application context在此基础上还提供了其余的功能。
如下是三种较常见的 ApplicationContext 实现方式:
一、ClassPathXmlApplicationContext:从classpath的XML配置文件中读取上下文,并生成上下文定义。应用程序上下文从程序环境变量中取得。
1
|
ApplicationContext context =
new
ClassPathXmlApplicationContext(“bean.xml”);
|
二、FileSystemXmlApplicationContext :由文件系统中的XML配置文件读取上下文。
1
|
ApplicationContext context =
new
FileSystemXmlApplicationContext(“bean.xml”);
|
三、XmlWebApplicationContext:由Web应用的XML文件读取上下文。
将Spring配置到应用开发中有如下三种方式:
在Spring框架中,依赖和服务须要在专门的配置文件来实现,我经常使用的XML格式的配置文件。这些配置文件的格式一般用<beans>
开头,而后一系列的
bean
定义和专门的应用配置选项组成。
SpringXML配置的主要目的时候是使全部的Spring组件均可以用xml文件的形式来进行配置。这意味着不会出现其余的Spring配置类型(好比声明的方式或基于Java Class的配置方式)
Spring的XML配置方式是使用被Spring命名空间的所支持的一系列的XML标签来实现的。Spring有如下主要的命名空间:context、beans、jdbc、tx、aop、mvc和aso。
1
2
3
4
5
6
7
8
9
|
<
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
>
|
下面这个web.xml仅仅配置了DispatcherServlet,这件最简单的配置便能知足应用程序配置运行时组件的需求。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<
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
>
|
Spring对Java配置的支持是由@Configuration注解和@Bean注解来实现的。由@Bean注解的方法将会实例化、配置和初始化一个新对象,这个对象将由Spring的IoC容器来管理。@Bean声明所起到的做用与<bean/> 元素相似。被@Configuration所注解的类则表示这个类的主要目的是做为bean定义的资源。被@Configuration声明的类能够经过在同一个类的内部调用@bean方法来设置嵌入bean的依赖关系。
最简单的@Configuration 声明类请参考下面的代码:
1
2
3
4
5
6
7
8
|
@Configuration
public
class
AppConfig
{
@Bean
public
MyService myService() {
return
new
MyServiceImpl();
}
}
|
对于上面的@Beans配置文件相同的XML配置文件以下:
1
2
3
|
<
beans
>
<
bean
id
=
"myService"
class
=
"com.howtodoinjava.services.MyServiceImpl"
/>
</
beans
>
|
上述配置方式的实例化方式以下:利用AnnotationConfigApplicationContext 类进行实例化
1
2
3
4
5
|
public
static
void
main(String[] args) {
ApplicationContext ctx =
new
AnnotationConfigApplicationContext(AppConfig.
class
);
MyService myService = ctx.getBean(MyService.
class
);
myService.doStuff();
}
|
要使用组件组建扫描,仅需用@Configuration进行注解便可:
1
2
3
4
5
|
@Configuration
@ComponentScan
(basePackages =
"com.howtodoinjava"
)
public
class
AppConfig {
...
}
|
在上面的例子中,com.acme包首先会被扫到,而后再容器内查找被@Component 声明的类,找到后将这些类按照Sring bean定义进行注册。
若是你要在你的web应用开发中选用上述的配置的方式的话,须要用AnnotationConfigWebApplicationContext 类来读取配置文件,能够用来配置Spring的Servlet监听器ContrextLoaderListener或者Spring MVC的DispatcherServlet。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
<
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
>
|
Spring在2.5版本之后开始支持用注解的方式来配置依赖注入。能够用注解的方式来替代XML方式的bean描述,能够将bean描述转移到组件类的内部,只须要在相关类上、方法上或者字段声明上使用注解便可。注解注入将会被容器在XML注入以前被处理,因此后者会覆盖掉前者对于同一个属性的处理结果。
注解装配在Spring中是默认关闭的。因此须要在Spring文件中配置一下才能使用基于注解的装配模式。若是你想要在你的应用程序中使用关于注解的方法的话,请参考以下的配置。
1
2
3
4
5
6
|
<
beans
>
<
context:annotation-config
/>
<!-- bean definitions go here -->
</
beans
>
|
在 <context:annotation-config/>标签配置完成之后,就能够用注解的方式在Spring中向属性、方法和构造方法中自动装配变量。
下面是几种比较重要的注解类型:
Spring Bean的生命周期简单易懂。在一个bean实例被初始化时,须要执行一系列的初始化操做以达到可用的状态。一样的,当一个bean不在被调用时须要进行相关的析构操做,并从bean容器中移除。
Spring bean factory 负责管理在spring容器中被建立的bean的生命周期。Bean的生命周期由两组回调(call back)方法组成。
Spring框架提供了如下四种方式来管理bean的生命周期事件:
使用customInit()
和 customDestroy()
方法管理
bean
生命周期的代码样例以下:
1
2
3
4
|
<
beans
>
<
bean
id
=
"demoBean"
class
=
"com.howtodoinjava.task.DemoBean"
init-method
=
"customInit"
destroy-method
=
"customDestroy"
></
bean
>
</
beans
>
|
更多内容请参考:Spring生命周期Spring Bean Life Cycle。
Spring容器中的bean能够分为5个范围。全部范围的名称都是自说明的,可是为了不混淆,仍是让咱们来解释一下:
全局做用域与Servlet中的session做用域效果相同。
更多内容请参考 : Spring Bean Scopes。
在Spring框架中,不管什么时候bean被使用时,当仅被调用了一个属性。一个明智的作法是将这个bean声明为内部bean。内部bean能够用setter注入“属性”和构造方法注入“构造参数”的方式来实现。
好比,在咱们的应用程序中,一个Customer类引用了一个Person类,咱们的要作的是建立一个Person的实例,而后在Customer内部使用。
1
2
3
4
5
6
|
public
class
Customer
{
private
Person person;
//Setters and Getters
}
|
1
2
3
4
5
6
7
8
|
public
class
Person
{
private
String name;
private
String address;
private
int
age;
//Setters and Getters
}
|
内部bean的声明方式以下:
1
2
3
4
5
6
7
8
9
10
|
<
bean
id
=
"CustomerBean"
class
=
"com.howtodoinjava.common.Customer"
>
<
property
name
=
"person"
>
<!-- This is inner bean -->
<
bean
class
=
"com.howtodoinjava.common.Person"
>
<
property
name
=
"name"
value
=
"lokesh"
/>
<
property
name
=
"address"
value
=
"India"
/>
<
property
name
=
"age"
value
=
"34"
/>
</
bean
>
</
property
>
</
bean
>
|
Spring框架并无对单例bean进行任何多线程的封装处理。关于单例bean的线程安全和并发问题须要开发者自行去搞定。但实际上,大部分的Spring bean并无可变的状态(好比Serview类和DAO类),因此在某种程度上说Spring的单例bean是线程安全的。若是你的bean有多种状态的话(好比 View Model 对象),就须要自行保证线程安全。
最浅显的解决办法就是将多态bean的做用域由“singleton”变动为“prototype”。
Spring提供了如下四种集合类的配置元素:
下面看一下具体的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
<
beans
>
<!-- Definition for javaCollection -->
<
bean
id
=
"javaCollection"
class
=
"com.howtodoinjava.JavaCollection"
>
<!-- java.util.List -->
<
property
name
=
"customList"
>
<
list
>
<
value
>INDIA</
value
>
<
value
>Pakistan</
value
>
<
value
>USA</
value
>
<
value
>UK</
value
>
</
list
>
</
property
>
<!-- java.util.Set -->
<
property
name
=
"customSet"
>
<
set
>
<
value
>INDIA</
value
>
<
value
>Pakistan</
value
>
<
value
>USA</
value
>
<
value
>UK</
value
>
</
set
>
</
property
>
<!-- java.util.Map -->
<
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
>
<!-- java.util.Properties -->
<
property
name
=
"customProperies"
>
<
props
>
<
prop
key
=
"admin"
>admin@nospam.com</
prop
>
<
prop
key
=
"support"
>support@nospam.com</
prop
>
</
props
>
</
property
>
</
bean
>
</
beans
>
|
第一种方法是使用以下面代码所示的<props> 标签:
1
2
3
4
5
6
7
8
9
10
11
|
<
bean
id
=
"adminUser"
class
=
"com.howtodoinjava.common.Customer"
>
<!-- java.util.Properties -->
<
property
name
=
"emails"
>
<
props
>
<
prop
key
=
"admin"
>admin@nospam.com</
prop
>
<
prop
key
=
"support"
>support@nospam.com</
prop
>
</
props
>
</
property
>
</
bean
>
|
也可用”util:”命名空间来从properties文件中建立出一个propertiesbean,而后利用setter方法注入bean的引用。
在Spring框架中,在配置文件中设定bean的依赖关系是一个很好的机制,Spring容器还能够自动装配合做关系bean之间的关联关系。这意味着Spring能够经过向Bean Factory中注入的方式自动搞定bean之间的依赖关系。自动装配能够设置在每一个bean上,也能够设定在特定的bean上。
下面的XML配置文件代表了如何根据名称将一个bean设置为自动装配:
1
|
<
bean
id
=
"employeeDAO"
class
=
"com.howtodoinjava.EmployeeDAOImpl"
autowire
=
"byName"
/>
|
除了bean配置文件中提供的自动装配模式,还可使用@Autowired
注解来自动装配指定的
bean
。在使用
@Autowired
注解以前须要在按照以下的配置方式在
Spring
配置文件进行配置才可使用。
1
|
<
context:annotation-config
/>
|
也能够经过在配置文件中配置AutowiredAnnotationBeanPostProcessor
达到相同的效果。
1
|
<
bean
class
=
"org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"
/>
|
配置好之后就可使用@Autowired
来标注了。
1
2
3
4
|
@Autowired
public
EmployeeDAOImpl ( EmployeeManager manager ) {
this
.manager = manager;
}
|
在Spring框架中共有5种自动装配,让咱们逐一分析。
要使用 @Autowired
,须要注册
AutowiredAnnotationBeanPostProcessor
,能够有如下两种方式来实现:
一、引入配置文件中的<bean>下引入 <context:annotation-config>
1
2
3
|
<
beans
>
<
context:annotation-config
/>
</
beans
>
|
二、在bean配置文件中直接引入AutowiredAnnotationBeanPostProcessor
1
2
3
|
<
beans
>
<
bean
class
=
"org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"
/>
</
beans
>
|
在产品级别的应用中,IoC容器可能声明了数十万了bean,bean与bean之间有着复杂的依赖关系。设值注解方法的短板之一就是验证全部的属性是否被注解是一项十分困难的操做。能够经过在<bean>中设置“dependency-check”来解决这个问题。
在应用程序的生命周期中,你可能不大愿意花时间在验证全部bean的属性是否按照上下文文件正确配置。或者你宁肯验证某个bean的特定属性是否被正确的设置。即便是用“dependency-check”属性也不能很好的解决这个问题,在这种状况下,你须要使用@Required
注解。
须要用以下的方式使用来标明bean的设值方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
class
EmployeeFactoryBean
extends
AbstractFactoryBean<Object>
{
private
String designation;
public
String getDesignation() {
return
designation;
}
@Required
public
void
setDesignation(String designation) {
this
.designation = designation;
}
//more code here
}
|
RequiredAnnotationBeanPostProcessor
是Spring中的后置处理用来验证被@Required
注解的bean属性是否被正确的设置了。在使用RequiredAnnotationBeanPostProcesso
来验证bean
属性以前,首先要在IoC
容器中对其进行注册:
1
|
<
bean
class
=
"org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"
/>
|
可是若是没有属性被用 @Required
注解过的话,后置处理器会抛出一个BeanInitializationException
异常。
@Autowired注解对自动装配什么时候何处被实现提供了更多细粒度的控制。@Autowired
注解能够像
@Required
注解、构造器同样被用于在
bean
的设值方法上自动装配
bean
的属性,一个参数或者带有任意名称或带有多个参数的方法。
好比,能够在设值方法上使用@Autowired
注解来替代配置文件中的
<property>
元素。当
Spring
容器在
setter
方法上找到
@Autowired
注解时,会尝试用
byType 自动装配。
固然咱们也能够在构造方法上使用@Autowired
注解。带有@Autowired
注解的构造方法意味着在建立一个bean时将会被自动装配,即使在配置文件中使用<constructor-arg>
元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public
class
TextEditor {
private
SpellChecker spellChecker;
@Autowired
public
TextEditor(SpellChecker spellChecker){
System.out.println(
"Inside TextEditor constructor."
);
this
.spellChecker = spellChecker;
}
public
void
spellCheck(){
spellChecker.checkSpelling();
}
}
|
下面是没有构造参数的配置方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<
beans
>
<
context:annotation-config
/>
<!-- Definition for textEditor bean without constructor-arg -->
<
bean
id
=
"textEditor"
class
=
"com.howtodoinjava.TextEditor"
>
</
bean
>
<!-- Definition for spellChecker bean -->
<
bean
id
=
"spellChecker"
class
=
"com.howtodoinjava.SpellChecker"
>
</
bean
>
</
beans
>
|
@Qualifier
注解意味着能够在被标注
bean
的字段上能够自动装配。
Qualifier注解能够用来取消Spring不能取消的bean应用。
下面的示例将会在Customer的person属性中自动装配person的值。
1
2
3
4
5
|
public
class
Customer
{
@Autowired
private
Person person;
}
|
下面咱们要在配置文件中来配置Person类。
1
2
3
4
5
6
7
8
9
|
<
bean
id
=
"customer"
class
=
"com.howtodoinjava.common.Customer"
/>
<
bean
id
=
"personA"
class
=
"com.howtodoinjava.common.Person"
>
<
property
name
=
"name"
value
=
"lokesh"
/>
</
bean
>
<
bean
id
=
"personB"
class
=
"com.howtodoinjava.common.Person"
>
<
property
name
=
"name"
value
=
"alex"
/>
</
bean
>
|
Spring
会知道要自动装配哪一个person bean么?不会的,可是运行上面的示例时,
会抛出下面的异常:
1
2
3
|
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of
type
[com.howtodoinjava.common.Person] is defined:
expected single matching bean but found 2: [personA, personB]
|
要解决上面的问题,须要使用 @Quanlifier
注解来告诉Spring容器要装配哪一个bean:
1
2
3
4
5
6
|
public
class
Customer
{
@Autowired
@Qualifier
(
"personA"
)
private
Person person;
}
|
请注意如下明显的区别:
ObjectCurrentlyInCreationException异常,由于在B对象被建立以前A对象是不能被建立的,反之亦然。因此Spring用设值注入的方法解决了循环依赖的问题,因对象的设值方法是在对象被建立以前被调用的。
Spring的ApplicationContext
提供了支持事件和代码中监听器的功能。
咱们能够建立bean用来监听在ApplicationContext
中发布的事件。ApplicationEven
t类和在ApplicationContext
接口
中处理的事件,若是一个bean实现了ApplicationListener
接口,当一个ApplicationEvent
被发布之后,bean会自动被通知。
1
2
3
4
5
6
7
8
|
public
class
AllApplicationEventListener
implements
ApplicationListener < ApplicationEvent >
{
@Override
public
void
onApplicationEvent(ApplicationEvent applicationEvent)
{
//process event
}
}
|
Spring 提供了如下5中标准的事件:
除了上面介绍的事件之外,还能够经过扩展ApplicationEvent
类来开发自定义的事件。
1
2
3
4
5
6
7
8
|
public
class
CustomApplicationEvent
extends
ApplicationEvent
{
public
CustomApplicationEvent ( Object source,
final
String msg )
{
super
(source);
System.out.println(
"Created a Custom event"
);
}
}
|
为了监听这个事件,还须要建立一个监听器:
1
2
3
4
5
6
7
|
public
class
CustomEventListener
implements
ApplicationListener < CustomApplicationEvent >
{
@Override
public
void
onApplicationEvent(CustomApplicationEvent applicationEvent) {
//handle event
}
}
|
以后经过applicationContext接口的publishEvent()方法来发布自定义事件。
1
2
|
CustomApplicationEvent customEvent =
new
CustomApplicationEvent(applicationContext,
"Test message"
);
applicationContext.publishEvent(customEvent);
|
在FileSystemResource
中须要给出spring-config.xml
文件在你项目中的相对路径或者绝对路径。在ClassPathResource
中spring会在ClassPath中自动搜寻配置文件,因此要把ClassPathResource
文件放在ClassPath下。
若是将spring-config.xml
保存在了src文件夹下的话,只需给出配置文件的名称便可,由于src文件夹是默认。
简而言之,ClassPathResource在环境变量中读取配置文件,FileSystemResource在配置文件中读取配置文件。
Spring框架中使用到了大量的设计模式,下面列举了比较有表明性的:
JmsTemplate
, JpaTemplate。
DispatcherServlet
来对请求进行分发。
BeanFactory
/ ApplicationContext
接口的核心理念。