目录
1、什么是 Spring 框架?Spring 框架有哪些主要模块?
5、BeanFactory 和 ApplicationContext 有什么区别?
13、Spring 框架中的单例 Beans 是线程安全的么?
14、请举例说明如何在 Spring 中注入一个 Java Collection?
15、如何向 Spring Bean 中注入一个 Java.util.Properties?
1、什么是 Spring 框架?Spring 框架有哪些主要模块?
- Spring 框架是一个为 Java 应用程序的开发提供了综合、广泛的基础性支持的 Java 平台。
- Spring 帮助开发者解决了开发中基础性的问题,使得开发人员可以专注于应用程序主业务逻辑的开发。
- Spring 框架本身亦是按照设计模式精心打造,这使得我们可以在开发环境中安心的集成 Spring 框 架,不必担心 Spring 是如何在后台进行工作的。
- Spring框架主要由七部分组成,分别是 Spring Core、 Spring AOP、 Spring ORM、 Spring DAO、Spring Context、 Spring Web和 Spring Web MVC。
2、使用 Spring 框架能带来哪些好处?
- 低侵入式设计,代码污染极低
- 独立于各种应用服务器,基于Spring框架的应用,可以真正实现一次编译,到处运行的承诺
- Spring的DI机制降低了业务对象替换的复杂性,提高了组件之间的解耦
- Spring的AOP支持允许将一些通用任务如安全、事务、日志等进行集中式管理,从而提供了更好的复用
- Spring的ORM和DAO提供了与第三方持久层框架的良好整合,并简化了底层的数据库访问
- Spring并不强制应用完全依赖于Spring,开发者可自由选用Spring框架的部分或全部
3、什么是控制反转(IOC)?什么是依赖注入?
控制反转(IOC):简单来说就是把复杂系统分解成相互合作的对象,这些对象类通过封装以后,内部实现对外部是透明的,从而降低了解决问题的复杂度,而且可以灵活地被重用和扩展。全部对象的控制权全部上缴给“第三方”IOC容器,所以,IOC容器成了整个系统的关键核心,它起到了一种类似“粘合剂”的作用,把系统中的所有对象粘合在一起发挥作用。
软件系统在没有引入IOC容器之前,对象A依赖于对象B,那么对象A在初始化或者运行到某一点的时候,自己必须主动去创建对象B或者使用已经创建的对象B。无论是创建还是使用对象B,控制权都在自己手上。
软件系统在引入IOC容器之后,这种情形就完全改变了,由于IOC容器的加入,对象A与对象B之间失去了直接联系,所以,当对象A运行到需要对象B的时候,IOC容器会主动创建一个对象B注入到对象A需要的地方。
通过前后的对比,我们不难看出来:对象A获得依赖对象B的过程,由主动行为变为了被动行为,控制权颠倒过来了,这就是“控制反转”这个名称的由来。
依赖注入(DI): 是IOC的别名,既然IOC是控制反转,那么到底是“哪些方面的控制被反转了呢?” 是“获得依赖对象的过程被反转了”。控制被反转之后,获得依赖对象的过程由自身管理变为了由IOC容器主动注入。于是,给“控制反转”取了一个更合适的名字叫做“依赖注入(Dependency Injection)”。实际上给出了实现IOC的方法:注入。所谓依赖注入,就是由IOC容器在运行期间,动态地将某种依赖关系注入到对象之中。
总结:依赖注入(DI)和控制反转(IOC)是从不同的角度的描述的同一件事情,就是指通过引入IOC容器,利用依赖关系注入的方式,实现对象之间的解耦。
参考资料:https://www.jianshu.com/p/294b5e845543
4、请解释下 Spring 框架中的 IOC是如何实现的?
IOC中最基本的技术就是“反射(Reflection)”编程,通俗来讲就是根据给出的类名来动态地生成对象。这种编程方式可以让对象在生成时才决定到底是哪一种对象。
我们可以把IOC容器的工作模式看做是工厂模式的升华,可以把IOC容器看作是一个工厂,这个工厂里要生产的对象都在配置文件中给出定义,然后利用编程语言的的反射编程,根据配置文件中给出的类名生成相应的对象。从实现来看,IOC是把以前在工厂方法里写死的对象生成代码,改变为由配置文件来定义,也就是把工厂和对象生成这两者独立分隔开来,目的就是提高灵活性和可维护性。
5、BeanFactory 和 ApplicationContext 有什么区别?
BeanFactory:
- BeanFactory 可以理解为含有 bean 集合的工厂类,包含了各种 bean 的定义,以便 在接收到客户端请求时将对应的 bean 实例化。
- BeanFactory 还能在实例化对象的时生成协作类之间的关系。此举将 bean 自身从bean客户端的 配置中解放出来。BeanFactory 还包含 了 bean 生命周期的控制,调用客户端的初始化方法(initialization methods)和销毁方法(destruction methods)。
ApplicationContext :
从表面上看,application context 如同 bean factory 一样具有 bean 定义、bean 关联关系的设置,根据请求分发 bean 的功能。但 applicationcontext 在此基础上还提供了其他的功能。
- 提供了支持国际化的文本消息
- 统一的资源文件读取方式
- 已在监听器中注册的 bean 的事件
ApplicationContext context = new
ClassPathXmlApplicationContext(“bean.xml”);
2、FileSystemXmlApplicationContext :由文件系统中的 XML 配置文件读取上下文。
ApplicationContext context = new
FileSystemXmlApplicationContext(“bean.xml”);
6、Spring 有几种配置方式?
将 Spring 配置到应用开发中有以下三种方式:
- 基于 XML 的配置
- 基于注解的配置
- 基于 Java 的配置
7、如何用基于 XML 配置的方式配置 Spring?
在 Spring 框架中,依赖和服务需要在专门的配置文件来实现,我常用的 XML 格式的配置文件。这 些配置文件的格式通常用<beans>开头,然后一系列的 bean 定义和专门的应用配置 选项组成。
8、如何用基于 Java 配置的方式配置 Spring?
@Configuration
public class AppConfig{
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
<beans>
<bean id="myService" class="com.somnus.services.MyServiceImpl"/>
</beans>
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
@Configuration
@ComponentScan(basePackages = "com.somnus")
public class AppConfig {
...
}
<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 commaor 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、怎样用注解的方式配置 Spring?
<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
- @Required:该注解应用于设值方法。
- @Autowired:该注解应用于有值设值方法、非设值方法、构造方法和变量。
- @Qualifier:该注解和@Autowired 注解搭配使用,用于消除特定 bean 自动装配的歧义。
- JSR-250 Annotations:Spring 支持基于 JSR-250 注解的以下注解,@Resource、@PostConstruct 和 @PreDestroy。
10、请解释 Spring Bean 的生命周期?
- 初始化之后调用的回调方法。
- 销毁之前调用的回调方法。
Spring 框架提供了以下四种方式来管理 bean 的生命周期事件:
- InitializingBean 和 DisposableBean 回调接口
- 针对特殊行为的其他 Aware 接口
- Bean 配置文件中的 Custom init()方法和 destroy()方法
- @PostConstruct 和@PreDestroy 注解方式
<beans>
<bean id="demoBean" class="com.somnus.task.DemoBean" initmethod="customInit" destroy-method="customDestroy"></bean>
</beans>
11
、
Spring Bean
的作用域之间有什么区别?
- singleton:这种 bean 范围是默认的,这种范围确保不管接受到多少个请求,每个容器中只有一个 bean 的实例,单例的模式由 bean factory 自身来维护。
- prototype:原形范围与单例范围相反,为每一个 bean 请求提供一个实例。
- request:在请求 bean 范围内会为每一个来自客户端的网络请求创建一个实例,在请求完成以后, bean 会失效并被垃圾回收器回收。
- Session:与请求范围类似,确保每个 session 中有一个 bean 的实例,在 session 过期后,bean 会随之失效。
- global- session:global-session 和 Portlet 应用相关。当你的应用部署在 Portlet 容器中工作时,它包含很多 portlet。如果 你想要声明让所有的 portlet 共用全局的存储变量的话,那么这全局变量需要存储在 global-session 中。全局作用域与 Servlet 中的session 作用域效果相同。
12、什么是 Spring inner beans?
public class Customer{
private Person person;
//Setters and Getters
}
public class Person{
private String name;
private String address;
private int age;
//Setters and Getters
}
<bean id="CustomerBean" class="com.somnus.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>
13、Spring 框架中的单例 Beans 是线程安全的么?
14、请举例说明如何在 Spring 中注入一个 Java Collection?
Spring 提供了以下四种集合类的配置元素:
- <list> : 该标签用来装配可重复的 list 值。
- <set> : 该标签用来装配没有重复的 set 值。
- <map>: 该标签可用来注入键和值可以为任何类型的键值对。
- <props> : 该标签支持注入键和值都是字符串类型的键值对。
下面看一下具体的例子:
<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>
15、如何向 Spring Bean 中注入一个 Java.util.Properties?
第一种方法是使用如下面代码所示的<props> 标签:
<bean id="adminUser" class="com.somnus.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>
16、请解释 Spring Bean 的自动装配?
<bean id="employeeDAO" class="com.howtodoinjava.EmployeeDAOImpl"
autowire="byName" />
<context:annotation-config />
<bean class
="org.springframework.beans.factory.annotation.AutowiredAnnotationBea
nPostProcessor"/>
@Autowired
public EmployeeDAOImpl ( EmployeeManager manager ) {
this.manager = manager;
}
17、请解释自动装配模式的区别?
在 Spring 框架中共有 5 种自动装配,让我们逐一分析。
- no:这是 Spring 框架的默认设置,在该设置下自动装配是关闭的,开发者需要自行在 bean 定义中用标签明确的设置依赖关系。
- byName:该选项可以根据 bean 名称设置依赖关系。当向一个 bean 中自动装配一个属性时,容器将根据 bean 的名称自动在配置文件中查询一个匹配的 bean。如果找到的话,就装配这个属性,如果没找到的话就报错。
- byType:该选项可以根据 bean 类型设置依赖关系。当向一个 bean 中自动装配一个属性时,容器将根据 bean 的类型自动在配置文件中查询一个匹配的 bean。如果找到的话,就装配这个属性,如果没找到的话就报错。
- constructor:构造器的自动装配和 byType 模式类似,但是仅仅适用于 与构造器有相同参数的bean,如果在容器中没有找到与构造器参数类型一致的 bean,那么将会抛出异常。
- autodetect:该模式自动探测使用构造器自动装配或者 byType 自动装配。首先,首先会尝试找合适的带参数的构造器,如果找到的话就是用构造器自动装配,如果在 bean 内部没有找到相应的构造器或者是无参构造器,容器就会自动选择 byTpe 的自动装配方式。
18、如何开启基于注解的自动装配?
<beans>
<context:annotation-config />
</beans>
<beans>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
19
、请举例解释
@Required
注解?
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
}
<bean
class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
20、请举例解释@Autowired 注解?
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();
}
}
<beans>
<context:annotation-config/>
<!-- Definition for textEditor bean without constructor-arg -->
<bean id="textEditor" class="com.howtodoinjava.TextEditor"/>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.howtodoinjava.SpellChecker"/>
</beans>
21、请举例说明@Qualifier 注解?
public class Customer{
@Autowired
private Person person;
}
<bean id="customer" class="com.somnus.common.Customer" />
<bean id="personA" class="com.somnus.common.Person" >
<property name="name" value="lokesh" />
</bean>
<bean id="personB" class="com.somnus.common.Person" >
<property name="name" value="alex" />
</bean>
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]
public class Customer{
@Autowired
@Qualifier("personA")
private Person person;
}
22、构造方法注入和设值注入有什么区别?
请注意以下明显的区别:
- 在设值注入方法支持大部分的依赖注入,如果我们仅需 要注入 int、string 和 long 型的变量,我们不要用设值的方法注入。对于基本类型,如果我们没有注入的话,可以为基本类型设置默认值。在构造方法 注入不支持大部分的依赖注入,因为在调用构造方法中必须传入正确的构造参数,否则的话为报错。
- 设值注入不会重写构造方法的值。如果我们对同一个变量同时使用了构造方法注入又使用了设置方法注入的话,那么构造方法将不能覆盖由设值方法注入的值。很明显,因为构造方法仅在对象被创建时调用。
- 在使用设值注入时有可能还不能保证某种依赖是否已经被注入,也就是说这时对象的依赖关系有可能是不完整的。而在另一种情况下,构造器注入则不允许生成依赖关系不完整的对象。
- 在设值注入时如果对象 A 和对象 B 互相依赖,在创建对象 A 时 Spring 会抛出sObjectCurrentlyInCreationException 异常,因为在 B 对象被创建之前 A 对象是不能被创建的,反之亦然。所以 Spring 用设值注入的方法解决了循环依赖的问题,因对象的设值方法是在对象被创建之前被调用的。
23、Spring 框架中有哪些不同类型的事件?
public class AllApplicationEventListener implements ApplicationListener
<ApplicationEvent>{
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent){
//process event
}
}
- 上下文更新事件(ContextRefreshedEvent):该事件会在 ApplicationContext 被初始化或者更新时发布。也可以在调用 ConfigurableApplicationContext 接口中的 refresh()方法时被触发。
- 上下文开始事件(ContextStartedEvent):当容器调用 ConfigurableApplicationContext 的Start()方法开始/重新开始容器时触发该事件。
- 上下文停止事件(ContextStoppedEvent):当容器调用 ConfigurableApplicationContext 的 Stop()方法停止容器时触发该事件。
- 上下文关闭事件(ContextClosedEvent):当 ApplicationContext 被关闭时触发该事件。容器被关闭时,其管理的所有单例 Bean 都被销毁。
- 请求处理事件(RequestHandledEvent):在 Web 应用中,当一个 http 请求(request)结束触发该事件。
除了上面介绍的事件以外,还可以通过扩展 ApplicationEvent 类来开发自定义的事件。
public class CustomApplicationEvent extends ApplicationEvent{
public CustomApplicationEvent ( Object source, final String msg ){
super(source);
System.out.println("Created a Custom event");
}
}
public class CustomEventListener implements ApplicationListener <CustomApplicationEvent >{
@Override
public void onApplicationEvent(CustomApplicationEvent applicationEvent) {
//handle event
}
}
CustomApplicationEvent customEvent = new
CustomApplicationEvent(applicationContext, "Test message");
applicationContext.publishEvent(customEvent);
24、FileSystemResource 和 ClassPathResource 有何区别?
25、Spring 框架中都用到了哪些设计模式?
Spring 框架中使用到了大量的设计模式,下面列举了比较有代表性的:
- 代理模式—在 AOP 和 remoting 中被用的比较多。
- 单例模式—在 spring 配置文件中定义的 bean 默认为单例模式。o 模板方法—用来解决代码重复的问题。比如. RestTemplate, JmsTemplate, JpaTempl ate。
- 前端控制器—Spring 提供了 DispatcherServlet 来对请求进行分发。
- 视图帮助(View Helper )—Spring 提供了一系列的 JSP 标签,高效宏来辅助将分散的代码整合在视图里。
- 依赖注入—贯穿于 BeanFactory / ApplicationContext 接口的核心理念。
- 工厂模式—BeanFactory 用来创建对象的实例
26、开发中主要使用 Spring 的什么技术 ?
27、简述 AOP 和 IOC 概念 ?
AOP: