一、什么是 Spring 框架?Spring 框架有哪些主要模块?
Spring 框架是一个为 Java 应用程序的开发提供了综合、普遍的基础性支持的 Java 平台。Spring帮助开发者解决了开发中基础性的问题,使得开发人员能够专一于应用程序的开发。Spring 框架自己亦是按照设计模式精心打造,这使得咱们能够在开发环境中安心的集成 Spring 框架,不必担忧 Spring 是如何在后台进行工做的。html
Spring 框架至今已集成了 20 多个模块。这些模块主要被分以下图所示的核心容器、数据访问/集成,、Web、AOP(面向切面编程)、工具、消息和测试模块。java
二、使用 Spring 框架能带来哪些好处?
下面列举了一些使用 Spring 框架带来的主要好处:web
三、什么是控制反转(IOC)?什么是依赖注入?面试
四、请解释下 Spring 框架中的 IOC?
Spring 中的 org.springframework.beans 包和 org.springframework.context 包构成了Spring 框架 IOC 容器的基础。spring
BeanFactory 接口提供了一个先进的配置机制,使得任何类型的对象的配置成为可能。数据库
ApplicationContex 接口对 BeanFactory(是一个子接口)进行了扩展,在 BeanFactory 的基础上添加了其余功能,好比与 Spring 的 AOP 更容易集成,也提供了处理 message resource的机制(用于国际化)、事件传播以及应用层的特别配置,好比针对 Web 应用的WebApplicationContext。编程
五、BeanFactory 和 ApplicationContext 有什么区别?
BeanFactory 能够理解为含有 bean 集合的工厂类。BeanFactory 包含了种 bean 的定义,以便在接收到客户端请求时将对应的 bean 实例化。json
BeanFactory 还能在实例化对象的时生成协做类之间的关系。此举将 bean 自身与 bean 客户端的配置中解放出来。BeanFactory 还包含了 bean 生命周期的控制,调用客户端的初始化方法(initialization methods)和销毁方法(destruction methods)。设计模式
从表面上看,application context 如同 bean factory 同样具备 bean 定义、bean 关联关系的设置,根据请求分发 bean 的功能。但 application context 在此基础上还提供了其余的功能。安全
如下是三种较常见的 ApplicationContext 实现方式:
一、ClassPathXmlApplicationContext:从 classpath 的 XML 配置文件中读取上下文,并生成上下文定义。应用程序上下文从程序环境变量中取得。
ApplicationContext context = new ClassPathXmlApplicationContext(“application.xml”);
二、FileSystemXmlApplicationContext :由文件系统中的 XML 配置文件读取上下文。
ApplicationContext context = new FileSystemXmlApplicationContext(“application.xml”);
三、XmlWebApplicationContext:由 Web 应用的 XML 文件读取上下文。
六、Spring 提供几种配置方式来设置元数据?
将 Spring 配置到应用开发中有如下三种方式:
七、如何使用 XML 配置的方式配置 Spring?
在 Spring 框架中,依赖和服务须要在专门的配置文件来实现,我经常使用的 XML 格式的配置文件。这些配置文件的格式一般用开头,而后一系列的 bean 定义和专门的应用配置选项组成。
SpringXML配置的主要目的时候是使全部的Spring组件均可以用xml文件的形式来进行配置。这意味着不会出现其余的 Spring 配置类型(好比声明的方式或基于 Java Class 的配置方式)
Spring 的 XML 配置方式是使用被 Spring 命名空间的所支持的一系列的 XML 标签来实现的。
Spring 有如下主要的命名空间:context、beans、jdbc、tx、aop、mvc 和 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>
下面这个 web.xml 仅仅配置了 DispatcherServlet,这件最简单的配置便能知足应用程序配置运行时组件的需求。
<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>
八、如何用基于 Java 配置的方式配置 Spring?
Spring 对 Java 配置的支持是由@Configuration 注解和@Bean 注解来实现的。由@Bean 注解的方法将会实例化、配置和初始化一个新对象,这个对象将由 Spring 的 IOC 容器来管理。
@Bean 声明所起到的做用与 元素相似。被@Configuration 所注解的类则表示这个类的主要目的是做为 bean 定义的资源。被@Configuration 声明的类能够经过在同一个类的内部调用@bean 方法来设置嵌入 bean 的依赖关系。
最简单的@Configuration 声明类请参考下面的代码:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
对于上面的@Beans 配置文件相同的 XML 配置文件以下:
<beans>
<bean id="myService" class="com.gupaoedu.services.MyServiceImpl"/>
</beans>
上述配置方式的实例化方式以下:利用 AnnotationConfigApplicationContext 类进行实例化
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx.getBean(MyService.class);
myService.doStuff();
}
要使用组件组建扫描,仅需用@Configuration 进行注解便可:
@Configuration
@ComponentScan(basePackages = "com.gupaoedu")
public class AppConfig {
}
在上面的例子中,com.springtest包首先会被扫到,而后再容器内查找被@Component 声明的类,找到后将这些类按照 Sring bean 定义进行注册。
如 果 你 要 在 你 的 web 应 用 开 发 中 选 用 上 述 的 配 置 的 方 式 的 话 , 需 要 用AnnotationConfigWebApplicationContext 类来读取配置文件,能够用来配置 Spring 的Servlet 监听器 ContrextLoaderListener 或者 Spring MVC 的 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.gupaoedu.AppConfig</param-value>
</context-param>
<!-- Bootstrap the root application context as usual using ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-cla
ss>
</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.gupaoedu.web.MVCConfig</param-value>
</init-param>
</servlet>
<!-- map all requests for /web/* to the dispatcher servlet -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/web/*</url-pattern>
</servlet-mapping>
</web-app>
九、怎样用注解的方式配置 Spring?
Spring 在 2.5 版本之后开始支持用注解的方式来配置依赖注入。能够用注解的方式来替代 XML方式的 bean 描述,能够将 bean 描述转移到组件类的内部,只须要在相关类上、方法上或者字段声明上使用注解便可。注解注入将会被容器在 XML 注入以前被处理,因此后者会覆盖掉前者对于同一个属性的处理结果。注解装配在 Spring 中是默认关闭的。因此须要在 Spring 文件中配置一下才能使用基于注解的装配模式。若是你想要在你的应用程序中使用关于注解的方法的话,请参考以下的配置。
<beans>
<context:annotation-config/>
<!-- bean definitions go here -->
</beans>
在标签配置完成之后,就能够用注解的方式在 Spring 中向属性、方法和构造方法中自动装配变-量。
下面是几种比较重要的注解类型:
十、请解释 Spring Bean 的生命周期?
Spring Bean 的生命周期简单易懂。在一个 bean 实例被初始化时,须要执行一系列的初始化操做以达到可用的状态。一样的,当一个 bean 不在被调用时须要进行相关的析构操做,并从 bean容器中移除。
Spring bean factory 负责管理在 spring 容器中被建立的 bean 的生命周期。Bean 的生命周期由两组回调(call back)方法组成。
Spring 框架提供了如下四种方式来管理 bean 的生命周期事件:
使用 customInit()和 customDestroy()方法管理 bean 生命周期的代码样例以下:
<beans>
<bean id="demoBean" class="com.gupaoedu.task.DemoBean" init-method="customInit" destroy-method="customDestroy"></bean>
</beans>
十一、Spring Bean 做用域之间的区别?
Spring 容器中的 bean 能够分为 5 个范围。全部范围的名称都是自说明的,可是为了不混淆,仍是让咱们来解释一下:
十二、什么是 Spring inner beans?
在 Spring 框架中,不管什么时候 bean 被使用时,当仅被调用了一个属性。一个明智的作法是将这个 bean 声明为内部 bean。内部 bean 能够用 setter 注入“属性”和构造方法注入“构造参数”的方式来实现。
好比,在咱们的应用程序中,一个 Customer 类引用了一个 Person 类,咱们的要作的是建立一个 Person 的实例,而后在 Customer 内部使用。
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 的声明方式以下:
<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>
1三、Spring 框架中的单例 Beans 是线程安全的么?
Spring 框架并无对单例 bean 进行任何多线程的封装处理。关于单例 bean 的线程安全和并发问题须要开发者自行去搞定。但实际上,大部分的 Spring bean 并无可变的状态(好比Serview类和DAO类),因此在某种程度上说Spring的单例bean是线程安全的。若是你
的bean有多种状态的话(好比 View Model 对象),就须要自行保证线程安全。最浅显的解决办法就是将多态 bean 的做用域由“singleton”变动为“prototype”。
1四、请举例说明如何在 Spring 中注入一个 Java 集合?
Spring 提供了如下四种集合类的配置元素:
下面看一下具体的例子:
<beans>
<!-- Definition for javaCollection -->
<bean id="javaCollection" class="com.gupaoedu.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@gupaoedu.com</prop>
<prop key="support">support@gupaoedu.com</prop>
</props>
</property>
</bean>
</beans>
1五、如何向 Spring Bean 中注入 java.util.Properties?
第一种方法是使用以下面代码所示的 标签:
<bean id="adminUser" class="com.howtodoinjava.common.Customer">
<!-- java.util.Properties -->
<property name="emails">
<props>
<prop key="admin">admin@gupaoedu.com</prop>
<prop key="support">support@gupaoedu.com</prop>
</props>
</property>
</bean>
也可用”util:”命名空间来从 properties 文件中建立出一个 propertiesbean,而后利用 setter方法注入 bean 的引用。
1六、请解释 Spring Bean 的自动装配?
在 Spring 框架中,在配置文件中设定 bean 的依赖关系是一个很好的机制,Spring 容器还能够自动装配合做关系 bean 之间的关联关系。这意味着 Spring 能够经过向 Bean Factory 中注入的方式自动搞定 bean 之间的依赖关系。自动装配能够设置在每一个 bean 上,也能够设定在特定的 bean 上。
下面的 XML 配置文件代表了如何根据名称将一个 bean 设置为自动装配:
<bean id="employeeDAO" class="com.gupaoedu.EmployeeDAOImpl" autowire="byName" />
除了 bean 配置文件中提供的自动装配模式,还可使用@Autowired 注解来自动装配指定的bean。在使用@Autowired 注解以前须要在按照以下的配置方式在 Spring 配置文件进行配置才可使用。<context:annotation-config />也能够经过在配置文件中配置 AutowiredAnnotationBeanPostProcessor 达到相同的效果。
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
配置好之后就可使用@Autowired 来标注了。
@Autowired
public EmployeeDAOImpl ( EmployeeManager manager ) {
this.manager = manager;
}
1七、请解释各类自动装配模式的区别?
在 Spring 框架中共有 5 种自动装配,让咱们逐一分析。
1八、如何开启基于注解的自动装配?
要使用 @Autowired,须要注册 AutowiredAnnotationBeanPostProcessor,能够有如下两种方式来实现:
一、引入配置文件中的下引入
<beans>
<context:annotation-config />
</beans>
二、在 bean 配置文件中直接引入 AutowiredAnnotationBeanPostProcessor
<beans>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
19 、 自动装配有哪些局限性?
自动装配有以下局限性:
20、在 Spring 中能够注入 null 或空字符串吗?
彻底能够。
2一、请举例解释@Required Annotation?
在产品级别的应用中,IOC 容器可能声明了数十万了 bean,bean 与 bean 之间有着复杂的依赖关系。设值注解方法的短板之一就是验证全部的属性是否被注解是一项十分困难的操做。能够经过在中设置“dependency-check”来解决这个问题。
在应用程序的生命周期中,你可能不大愿意花时间在验证全部 bean 的属性是否按照上下文文件正 确 配 置 。 或 者 你 宁 可 验 证 某 个 bean 的 特 定 属 性 是 否 被 正 确 的 设 置 。 即 使 是 用“dependency-check”属性也不能很好的解决这个问题,在这种状况下,你须要使用@Required 注解。
须要用以下的方式使用来标明 bean 的设值方法。
public class EmployeeFactoryBean extends AbstractFactoryBean<Object> {
private String designation;
public String getDesignation() {
return designation;
}
@Required
public void setDesignation(String designation) {
this.designation = designation;
}
}
RequiredAnnotationBeanPostProcessor 是 Spring 中的后置处理用来验证被@Required 注解的 bean 属性是否被正确的设置了。在使用 RequiredAnnotationBeanPostProcesso 来验证bean 属性以前,首先要在 IOC 容器中对其进行注册:
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />
但 是 如 果 没 有 属 性 被 用 @Required 注 解 过 的 话 , 后 置 处 理 器 会 抛 出 一 个BeanInitializationException 异常。
2二、请举例解释@Autowired 注解?
@Autowired 注解对自动装配什么时候何处被实现提供了更多细粒度的控制。@Autowired 注解能够像@Required 注解、构造器同样被用于在 bean 的设值方法上自动装配 bean 的属性,一个参数或者带有任意名称或带有多个参数的方法。
好比,能够在设值方法上使用@Autowired 注解来替代配置文件中的 元素。当 Spring 容器在setter 方法上找到@Autowired 注解时,会尝试用 byType 自动装配。
固然咱们也能够在构造方法上使用@Autowired 注解。带有@Autowired 注解的构造方法意味着在建立一个 bean 时将会被自动装配,即使在配置文件中使用 元素。
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.gupaoedu.TextEditor"></bean>
<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.gupaoedu.SpellChecker"></bean>
</beans>
2三、请举例说明@Qualifier 注解?
@Qualifier 注解意味着能够在被标注 bean 的字段上能够自动装配。Qualifier 注解能够用来取消 Spring 不能取消的 bean 应用。下面的示例将会在 Customer 的 person 属性中自动装配 person 的值。
public class Customer {
@Autowired
private Person person;
}
下面咱们要在配置文件中来配置 Person 类。
<bean id="customer" class="com.gupaoedu.common.Customer" />
<bean id="personA" class="com.gupaoedu.common.Person" >
<property name="name" value="lokesh" />
</bean>
<bean id="personB" class="com.gupaoedu.common.Person" >
<property name="name" value="alex" />
</bean>
Spring 会知道要自动装配哪一个 person bean 么?不会的,可是运行上面的示例时,会抛出下面的异常:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:No unique bean of type [com.gupaoedu.common.Person] is defined:expected single matching bean but found 2: [personA, personB]
要解决上面的问题,须要使用 @Quanlifier 注解来告诉 Spring 容器要装配哪一个 bean:
public class Customer {
@Autowired
@Qualifier("personA")
private Person person;
}
2四、构造方法注入和设值注入有什么区别?
请注意如下明显的区别:
因此 Spring 用设值注入的方法解决了循环依赖的问题,因对象的设值方法是在对象被建立以前被调用的。
2五、Spring 框架中有哪些不一样类型的事件?
Spring 的 ApplicationContext 提供了支持事件和代码中监听器的功能。咱们能够建立 bean 用来监听在 ApplicationContext 中发布的事件。ApplicationEvent 类和在 ApplicationContext 接口中处理的事件,若是一个 bean 实现了 ApplicationListener 接口,当一个 ApplicationEvent 被发布之后,bean 会自动被通知。
public class AllApplicationEventListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
//process event
}
}
Spring 提供了如下 5 中标准的事件:
除了上面介绍的事件之外,还能够经过扩展 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
}
}
以后经过 applicationContext 接口的 publishEvent()方法来发布自定义事件。
CustomApplicationEvent customEvent = new CustomApplicationEvent(applicationContext,"Test message");
applicationContext.publishEvent(customEvent);
2六、FileSystemResource 和 ClassPathResource 有何区别?
在 FileSystemResource 中须要给出 spring-config.xml 文件在你项目中的相对路径或者绝对路径。在 ClassPathResource 中 spring 会在 ClassPath 中自动搜寻配置文件,因此要把ClassPathResource 文件放在 ClassPath 下。
若是将 spring-config.xml 保存在了 src 文件夹下的话,只需给出配置文件的名称便可,由于 src文件夹是默认。简而言之,ClassPathResource 在环境变量中读取配置文件,FileSystemResource 在配置文件中读取配置文件。
2七、Spring 框架中都用到了哪些设计模式?
Spring 框架中使用到了大量的设计模式,下面列举了比较有表明性的:
2八、在 Spring 框架中如何更有效的使用 JDBC?
使用Spring JDBC框架,资源管理以及错误处理的代价都会减轻。开发人员只需经过statements和 queries 语句从数据库中存取数据。Spring 框架中经过使用模板类能更有效的使用 JDBC,也就是所谓的 JdbcTemplate。
2九、Spring5 新特性