Java Spring面试问题与解答

This post will help you get through Spring interview Questions explaining the core concepts in detail.
这篇文章将帮助你通过 Spring 面试问题 解释详细的核心概念。(zh_CN)

Spring Framework is one of the most popular Java EE framework for web applications. Dependency Injection and Aspect Oriented Programming are at the heart of Spring framework. If you are good in Spring Framework, chances of getting selected gets high.
Spring Framework 是最流行的 Web 应用程序 Java EE 框架之一。 依赖注入面向方面编程是 Spring 框架的核心。如果你擅长 Spring Framework,那么获得选择的机会就会很高。(zh_CN)

You should bookmark this post because Spring Framework is a lot bigger and chances are that I will keep on adding more questions to this list and you don’t want to miss them out.
你应该将这篇文章加入书签,因为 Spring Framework 要大得多,我可能会继续在这个列表中添加更多问题,你不想错过它们。(zh_CN)

1.What is Spring Framework?

1. 什么是 Spring Framework?(zh_CN)

Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.
Spring 是使用最广泛的 Java EE 框架之一。 Spring 框架核心概念是“依赖注入”和“面向方面编程”。(zh_CN)

Spring framework can be used in normal java applications also to achieve loose coupling between different components by implementing dependency injection and we can perform cross cutting tasks such as logging and authentication using spring support for aspect oriented programming.
Spring 框架也可以在普通的 java 应用程序中使用,通过实现依赖注入来实现不同组件之间的松散耦合,我们可以使用 spring 支持面向方面编程来执行交叉切割任务,例如日志记录和身份验证。(zh_CN)

I like spring because it provides a lot of features and different modules for specific tasks such as Spring MVC and Spring JDBC. Since it’s an open source framework with a lot of online resources and active community members, working with Spring framework is easy and fun at same time.
我喜欢 spring,因为它为 Spring MVC 和 Spring JDBC 等特定任务提供了许多功能和不同的模块。由于它是一个包含大量在线资源和活跃社区成员的开源框架,因此使用 Spring 框架既简单又有趣。(zh_CN)

2.What are some of the important features and advantages of Spring Framework?

2.Spring Framework 的一些重要特性和优势是什么?(zh_CN)

Spring Framework is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.
Spring Framework 构建于两个设计概念之上 - 依赖注入和面向方面编程。(zh_CN)

Some of the features of spring framework are:
spring 框架的一些特性是:(zh_CN)

  • Lightweight and very little overhead of using framework for our development.
  • 使用框架进行开发的轻量级和非常小的开销。(zh_CN)
  • Dependency Injection or Inversion of Control to write components that are independent of each other, spring container takes care of wiring them together to achieve our work.
  • 依赖注入或控制反转来编写彼此独立的组件,spring 容器负责将它们连接在一起以实现我们的工作。(zh_CN)
  • Spring IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
  • Spring IoC 容器管理 Spring Bean 生命周期和项目特定配置,例如 JNDI 查找。(zh_CN)
  • Spring MVC framework can be used to create web applications as well as restful web services capable of returning XML as well as JSON response.
  • Spring MVC 框架可用于创建 Web 应用程序以及能够返回 XML 和 JSON 响应的 restful Web 服务。(zh_CN)
  • Support for transaction management, JDBC operations, File uploading, Exception Handling etc with very little configurations, either by using annotations or by spring bean configuration file.
  • 通过使用注释或 spring bean 配置文件,支持事务管理,JDBC 操作,文件上载,异常处理等,配置非常少。(zh_CN)

Some of the advantages of using Spring Framework are:
使用 Spring Framework 的一些优点是:(zh_CN)

  • Reducing direct dependencies between different components of the application, usually Spring IoC container is responsible for initializing resources or beans and inject them as dependencies.
  • 减少应用程序的不同组件之间的直接依赖关系,通常 Spring IoC 容器负责初始化资源或 bean 并将它们作为依赖项注入。(zh_CN)
  • Writing unit test cases are easy in Spring framework because our business logic doesn’t have direct dependencies with actual resource implementation classes. We can easily write a test configuration and inject our mock beans for testing purposes.
  • 在 Spring 框架中编写单元测试用例很容易,因为我们的业务逻辑与实际的资源实现类没有直接的依赖关系。我们可以轻松编写测试配置并注入我们的模拟 bean 用于测试目的。(zh_CN)
  • Reduces the amount of boiler-plate code, such as initializing objects, open/close resources. I like JdbcTemplate class a lot because it helps us in removing all the boiler-plate code that comes with JDBC programming.
  • 减少重复代码的数量,例如初始化对象,打开/关闭资源。我非常喜欢 JdbcTemplate 类,因为它有助于我们删除 JDBC 编程附带的所有样板代码。(zh_CN)
  • Spring framework is divided into several modules, it helps us in keeping our application lightweight. For example, if we don’t need Spring transaction management features, we don’t need to add that dependency in our project.
  • Spring 框架分为几个模块,它有助于我们保持应用程序的轻量级。例如,如果我们不需要 Spring 事务管理功能,我们就不需要在项目中添加该依赖项。(zh_CN)
  • Spring framework support most of the Java EE features and even much more. It’s always on top of the new technologies, for example there is a Spring project for Android to help us write better code for native android applications. This makes spring framework a complete package and we don’t need to look after different framework for different requirements.
  • Spring 框架支持大多数 Java EE 功能甚至更多功能。它总是在新技术之上,例如,有一个 Android 的 Spring 项目,可以帮助我们为原生 Android 应用程序编写更好的代码。这使得 spring 框架成为一个完整的包,我们不需要为不同的需求提供不同的框架。(zh_CN)


What do you understand by Dependency Injection?


Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.

Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable components and easy unit testing.
使用依赖注入的一些好处是:关注点分离,Boilerplate 代码减少,可配置组件和简单的单元测试。(zh_CN)

Read more at Dependency Injection Tutorial. We can also use Google Guice for Dependency Injection to automate the process of dependency injection. But in most of the cases we are looking for more than just dependency injection and that’s why Spring is the top choice for this.
阅读[依赖注入教程](。我们还可以使用[Google Guice for Dependency Injection](自动执行依赖注入过程。但在大多数情况下,我们寻求的不仅仅是依赖注入,这就是为什么Spring是最佳选择。(zh_CN)


How do we implement DI in Spring Framework?

我们如何在 Spring Framework 中实现 DI?(zh_CN)

We can use Spring XML based as well as Annotation based configuration to implement DI in spring applications. For better understanding, please read Spring Dependency Injection example where you can learn both the ways with JUnit test case. The post also contains sample project zip file, that you can download and play around to learn more.
我们可以使用基于 Spring XML 和基于 Annotation 的配置来在 spring 应用程序中实现 DI。为了更好地理解,请阅读[Spring Dependency Injection](示例,其中您可以了解JUnit测试用例的两种方法。该帖子还包含示例项目zip文件,您可以下载和播放以了解更多信息。(zh_CN)


What are the benefits of using Spring Tool Suite?

使用 Spring Tool Suite 有什么好处?(zh_CN)

We can install plugins into Eclipse to get all the features of Spring Tool Suite. However STS comes with Eclipse with some other important stuffs such as Maven support, Templates for creating different types of Spring projects and tc server for better performance with Spring applications.
我们可以在 Eclipse 中安装插件以获得 Spring Tool Suite 的所有功能。然而,STS 附带了 Eclipse 以及一些其他重要的东西,例如 Maven 支持,用于创建不同类型的 Spring 项目的模板和用于 Spring 应用程序的更好性能的 tc 服务器。(zh_CN)

I like STS because it highlights the Spring components and if you are using AOP pointcuts and advices, then it clearly shows which methods will come under the specific pointcut. So rather than installing everything on our own, I prefer using STS when developing Spring based applications.
我喜欢 STS,因为它突出了 Spring 组件,如果你正在使用 AOP 切入点和建议,那么它清楚地显示了特定切入点下的哪些方法。因此,我宁愿在开发基于 Spring 的应用程序时使用 STS,而不是自己安装所有内容。(zh_CN)


Name some of the important Spring Modules?

列举一些重要的 Spring 模块?(zh_CN)

Some of the important Spring Framework modules are:
一些重要的 Spring Framework 模块是:(zh_CN)

  • Spring Context – for dependency injection.
  • Spring Context - 用于依赖注入。(zh_CN)
  • Spring AOP – for aspect oriented programming.
  • Spring AOP - 用于面向方面的编程。(zh_CN)
  • Spring DAO – for database operations using DAO pattern
  • Spring DAO - 用于使用 DAO 模式的数据库操作(zh_CN)
  • Spring JDBC – for JDBC and DataSource support.
  • Spring JDBC - 用于 JDBC 和 DataSource 支持。(zh_CN)
  • Spring ORM – for ORM tools support such as Hibernate
  • Spring ORM - 用于 ORM 工具支持,如 Hibernate(zh_CN)
  • Spring Web Module – for creating web applications.
  • Spring Web Module - 用于创建 Web 应用程序。(zh_CN)
  • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.
  • Spring MVC - 用于创建 Web 应用程序,Web 服务等的 Model-View-Controller 实现。(zh_CN)


What do you understand by Aspect Oriented Programming?


Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
企业应用程序有一些常见的横切关注点,适用于不同类型的对象和应用程序模块,如日志记录,事务管理,数据验证,身份验证等。在面向对象编程中,应用程序的模块化是通过类实现的,而在 AOP 应用程序中模块化由 Aspects 实现,它们被配置为跨越不同的类方法。(zh_CN)

AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data. Read more about Spring AOP support at Spring AOP Example.
AOP 从普通面向对象编程中不可能的类中获取横切任务的直接依赖性。例如,我们可以有一个单独的日志记录类,但类再次调用这些方法来记录数据。在[Spring AOP 示例](上阅读有关Spring AOP 支持的更多信息。(zh_CN)


What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?

AOP 中的 Aspect,Advice,Pointcut,JointPoint 和 Advice Arguments 是什么?(zh_CN)

Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
Aspect :Aspect 是一个实现交叉问题的类,例如事务管理。方面可以是配置的普通类,然后在 Spring Bean 配置文件中配置,或者我们可以使用 Spring AspectJ 支持将类声明为 Aspect 使用@Aspect 注解。(zh_CN)

Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring interceptors or Servlet Filters.
建议:建议是针对特定连接点采取的操作。在编程方面,它们是在应用程序中达到具有匹配切入点的特定连接点时执行的方法。您可以将建议视为[Spring interceptors](或[Servlet Filters]( / 1933 / java 的 servlet 的过滤器 - 例如教程)。(zh_CN)

Pointcut: Pointcut are regular expressions that is matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
切入点:切入点是与连接点匹配的正则表达式,用于确定是否需要执行建议。 Pointcut 使用与连接点匹配的不同类型的表达式。 Spring 框架使用 AspectJ 切入点表达式语言来确定将应用通知方法的连接点。(zh_CN)

Join Point: A join point is the specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.
Join Point :连接点是应用程序中的特定点,例如方法执行,异常处理,更改对象变量值等。在 Spring AOP 中,连接点始终是方法的执行。(zh_CN)

Advice Arguments: We can pass arguments in the advice methods. We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where argument type is determined.
建议参数:我们可以在通知方法中传递参数。我们可以在切入点中使用 args()表达式来应用于与参数模式匹配的任何方法。如果我们使用它,那么我们需要在确定参数类型的 advice 方法中使用相同的名称。(zh_CN)

These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.
这些概念最初似乎令人困惑,但如果你经历[Spring Aspect,Advice Example](然后你可以轻松地与他们联系。(zh_CN)


What is the difference between Spring AOP and AspectJ AOP?

Spring AOP 和 AspectJ AOP 有什么区别?(zh_CN)

AspectJ is the industry-standard implementation for Aspect Oriented Programming whereas Spring implements AOP for some cases. Main differences between Spring AOP and AspectJ are:
AspectJ 是面向方面编程的行业标准实现,而 Spring 在某些情况下实现了 AOP。 Spring AOP 和 AspectJ 之间的主要区别是:(zh_CN)

  • Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
  • Spring AOP 比 AspectJ 更易于使用,因为我们不需要担心编织过程。(zh_CN)
  • Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
  • Spring AOP 支持 AspectJ 注释,因此如果您熟悉 AspectJ,那么使用 Spring AOP 会更容易。(zh_CN)
  • Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
  • Spring AOP 仅支持基于代理的 AOP,因此它只能应用于方法执行连接点。 AspectJ 支持各种切入点。(zh_CN)
  • One of the shortcoming of Spring AOP is that it can be applied only to the beans created through Spring Context.
  • Spring AOP 的一个缺点是它只能应用于通过 Spring Context 创建的 bean。(zh_CN)


What is Spring IoC Container?

什么是 Spring IoC Container?(zh_CN)

Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use.
控制反转(IoC)是实现对象依赖关系之间松散耦合的机制。为了在运行时实现对象的松耦合和动态绑定,对象定义了由其他汇编器对象注入的依赖关系。 Spring IoC 容器是将依赖项注入对象并使其可供我们使用的程序。(zh_CN)

Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Spring Framework IoC 容器类是其中的一部分org.springframework.beansorg.springframework.context 包并为我们提供了解耦对象依赖关系的不同方法。(zh_CN)

Some of the useful ApplicationContext implementations that we use are;
我们使用的一些有用的 ApplicationContext 实现是;(zh_CN)

  • AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
  • AnnotationConfigApplicationContext: 对于使用基于注释的配置的独立 Java 应用程序。(zh_CN)
  • ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
  • ClassPathXmlApplicationContext: 对于使用基于 XML 的配置的独立 Java 应用程序。(zh_CN)
  • FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
  • FileSystemXmlApplicationContext: 与 ClassPathXmlApplicationContext 类似,不同之处在于可以从文件系统中的任何位置加载 xml 配置文件。(zh_CN)
  • AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.
  • AnnotationConfigWebApplicationContextXmlWebApplicationContext 用于 Web 应用程序。(zh_CN)


What is a Spring Bean?

什么是 Spring Bean?(zh_CN)

Any normal java class that is initialized by Spring IoC container is called Spring Bean. We use Spring ApplicationContext to get the Spring Bean instance.
由 Spring IoC 容器初始化的任何普通 java 类都称为 Spring Bean。我们用 SpringApplicationContext 获取 Spring Bean 实例。(zh_CN)

Spring IoC container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.
Spring IoC 容器管理 Spring Bean 的生命周期,bean 作用域以及在 bean 中注入任何所需的依赖项。(zh_CN)


What is the importance of Spring bean configuration file?

Spring bean 配置文件的重要性是什么?(zh_CN)

We use Spring Bean configuration file to define all the beans that will be initialized by Spring Context. When we create the instance of Spring ApplicationContext, it reads the spring bean xml file and initialize all of them. Once the context is initialized, we can use it to get different bean instances.
我们使用 Spring Bean 配置文件来定义将由 Spring Context 初始化的所有 bean。当我们创建 Spring ApplicationContext 的实例时,它会读取 spring bean xml 文件并初始化所有这些文件。初始化上下文后,我们可以使用它来获取不同的 bean 实例。(zh_CN)

Apart from Spring Bean configuration, this file also contains spring MVC interceptors, view resolvers and other elements to support annotations based configurations.
除了 Spring Bean 配置,该文件还包含 spring MVC 拦截器,视图解析器和其他元素,以支持基于注释的配置。(zh_CN)


What are different ways to configure a class as Spring Bean?

将类配置为 Spring Bean 有哪些不同的方法?(zh_CN)

There are three different ways to configure Spring Bean.
配置 Spring Bean 有三种不同的方法。(zh_CN)

  1. XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean. For example:
  2. XML 配置:这是最流行的配置,我们可以在上下文文件中使用 bean 元素来配置 Spring Bean。例如:(zh_CN)


  3. Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:

  4. 基于 Java 的配置:如果您只使用注释,则可以使用配置 Spring bean@Bean 注解。此注释用于@Configuration 用于配置 spring bean 的类。示例配置是:(zh_CN)

    @Configuration @ComponentScan(value=”com.journaldev.spring.main”) public class MyConfiguration { @Bean public MyService getService(){ return new MyService(); } }

To get this bean from spring context, we need to use following code snippet:
要从 spring 上下文获取此 bean,我们需要使用以下代码片段:(zh_CN)

 AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(         MyConfiguration.class); MyService service = ctx.getBean(MyService.class);
  1. Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes. For example:
  2. 基于注释的配置:我们还可以使用@Component,@ Service,@ Repository 和@Controller 注释与类来配置它们作为 spring bean。对于这些,我们需要提供基本包位置来扫描这些类。例如:(zh_CN)

    <context:component-scan base-package=”com.journaldev.spring” />


What are different scopes of Spring Bean?

Spring Bean 有哪些不同的范围?(zh_CN)

There are five scopes defined for Spring Beans.
为 Spring Beans 定义了五个范围。(zh_CN)

  1. singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
  2. [singleton](只为每个容器创建一个 bean 实例。这是 spring bean 的默认范围。使用此范围时,请确保 spring bean 没有共享实例变量,否则可能会导致数据不一致问题,因为它不是线程安全的。(zh_CN)
  3. prototype: A new instance will be created every time the bean is requested.
  4. prototype :每次请求 bean 时都会创建一个新实例。(zh_CN)
  5. request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
  6. 请求:这与原型范围相同,但它意味着用于 Web 应用程序。将为每个 HTTP 请求创建一个新的 bean 实例。(zh_CN)
  7. session: A new bean will be created for each HTTP session by the container.
  8. session :将为容器的每个 HTTP 会话创建一个新 bean。(zh_CN)
  9. global-session: This is used to create global session beans for Portlet applications.
  10. global-session :用于为 Portlet 应用程序创建全局会话 bean。(zh_CN)

Spring Framework is extendable and we can create our own scopes too, however most of the times we are good with the scopes provided by the framework.
Spring Framework 是可扩展的,我们也可以创建自己的作用域,但是大多数时候我们都很好地使用框架提供的作用域。(zh_CN)

To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based configurations.
要设置 spring bean 范围,我们可以在 bean 元素中使用“scope”属性,或者为基于注释的配置使用@Scope 注释。(zh_CN)


What is Spring Bean life cycle?

什么是 Spring Bean 生命周期?(zh_CN)

Spring Beans are initialized by Spring Container and all the dependencies are also injected. When context is destroyed, it also destroys all the initialized beans. This works well in most of the cases but sometimes we want to initialize other resources or do some validation before making our beans ready to use. Spring framework provides support for post-initialization and pre-destroy methods in spring beans.
Spring Bean 初始化 Spring Bean,并且还注入了所有依赖项。当上下文被破坏时,它也会破坏所有已初始化的 bean。这在大多数情况下运行良好,但有时我们想要初始化其他资源或在使我们的 bean 准备好使用之前进行一些验证。 Spring 框架为 spring bean 中的 post-initialization 和 pre-destroy 方法提供支持。(zh_CN)

We can do this by two ways – by implementing InitializingBean and DisposableBean interfaces or using init-method and destroy-method attribute in spring bean configurations. For more details, please read Spring Bean Life Cycle Methods.
我们可以通过两种方式实现这一目标 - 通过实施InitializingBeanDisposableBean 接口或在 spring bean 配置中使用 init-method destroy-method 属性。有关更多详细信息,请阅读[Spring Bean 生命周期方法](。(zh_CN)


How to get ServletContext and ServletConfig object in a Spring Bean?

如何在 Spring Bean 中获取 ServletContext 和 ServletConfig 对象?(zh_CN)

There are two ways to get Container specific objects in the spring bean.
有两种方法可以在 spring bean 中获取 Container 特定对象。(zh_CN)

  1. Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
  2. 为这些 ServletContextAware 和 ServletConfigAware 接口实现 Spring * Aware 接口,请参阅[Spring Aware Interfaces](
  3. Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
  4. 运用@Autowired 带有 bean 类型变量的注释ServletContextServletConfig. 它们仅适用于 servlet 容器特定环境。(zh_CN)

    @Autowired ServletContext servletContext;


What is Bean wiring and @Autowired annotation?

什么是 Bean 接线和@Autowired 注释?(zh_CN)

The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.
初始化时注入 spring bean 依赖项的过程称为 Spring Bean Wiring。(zh_CN)

Usually it’s best practice to do the explicit wiring of all the bean dependencies, but spring framework also supports autowiring. We can use @Autowired annotation with fields or methods for autowiring byType. For this annotation to work, we also need to enable annotation based configuration in spring bean configuration file. This can be done by context:annotation-config element.
通常,最佳做法是对所有 bean 依赖项进行显式连接,但 spring 框架也支持自动装配。我们可以用@Autowired 带有自动装配的字段或方法的注释。为了使这个注释起作用,我们还需要在 spring bean 配置文件中启用基于注释的配置。这可以通过 context:annotation-config 元素来完成。(zh_CN)

For more details about @Autowired annotation, please read Spring Autowire Example.
有关的更多详细信息@Autowired 注释,请阅读[Spring Autowire 示例](。(zh_CN)


What are different types of Spring Bean autowiring?

什么是不同类型的 Spring Bean 自动装配?(zh_CN)

There are four types of autowiring in Spring framework.
Spring 框架中有四种类型的自动装配。(zh_CN)

  1. autowire byName
  2. autowire byType
  3. autowire by constructor
  4. 由构造函数自动装配(zh_CN)
  5. autowiring by @Autowired and @Qualifier annotations
  6. 通过 @Autowired @ Qualifier 注释自动装配(zh_CN)

Prior to Spring 3.1, autowire by autodetect was also supported that was similar to autowire by constructor or byType. For more details about these options, please read Spring Bean Autowiring.
在 Spring 3.1 之前,还支持 autodeire by autodetect ,类似于构造函数或 byType 的 autowire。有关这些选项的更多详细信息,请阅读[Spring Bean Autowiring](。(zh_CN)


Does Spring Bean provide thread safety?

Spring Bean 是否提供线程安全性?(zh_CN)

The default scope of Spring bean is singleton, so there will be only one instance per context. That means that all the having a class level variable that any thread can update will lead to inconsistent data. Hence in default mode spring beans are not thread-safe.
Spring bean 的默认范围是 singleton,因此每个上下文只有一个实例。这意味着所有拥有任何线程可以更新的类级别变量都将导致数据不一致。因此,在默认模式下,spring bean 不是线程安全的。(zh_CN)

However we can change spring bean scope to request, prototype or session to achieve thread-safety at the cost of performance. It’s a design decision and based on the project requirements.
但是我们可以将 spring bean 范围更改为请求,原型或会话,以牺牲性能为代价来实现线程安全。这是一个设计决策,并基于项目要求。(zh_CN)


What is a Controller in Spring MVC?

什么是 Spring MVC 中的 Controller?(zh_CN)

Just like MVC design pattern, Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
就像 MVC 设计模式一样,Controller 是负责处理所有客户端请求并将它们发送到配置资源来处理它的类。在 Spring MVC 中,org.springframework.web.servlet.DispatcherServlet 是前端控制器类,它基于 spring bean 配置初始化上下文。(zh_CN)

A Controller class is responsible to handle different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.
Controller 类负责根据请求映射处理不同类型的客户端请求。我们可以使用创建一个控制器类@Controller 注解。通常它用于@RequestMapping 注释,用于定义特定 URI 映射的处理程序方法。(zh_CN)


What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?

Spring 中的@ Component,@ Controller,@ Repository 和@Service 注释有什么区别?(zh_CN)

@Component is used to indicate that a class is a component. These classes are used for auto detection and configured as bean, when annotation based configurations are used.
@组件用于指示类是组件。当使用基于注释的配置时,这些类用于自动检测并配置为 bean。(zh_CN)

@Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.
@Controller 是一种特定类型的组件,用于 MVC 应用程序,主要用于 RequestMapping 注释。(zh_CN)

@Repository annotation is used to indicate that a component is used as repository and a mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern implementation classes.
@存储库注释用于指示组件用作存储库以及用于存储/检索/搜索数据的机制。我们可以将这个注释应用于 DAO 模式实现类。(zh_CN)

@Service is used to indicate that a class is a Service. Usually the business facade classes that provide some services are annotated with this.

We can use any of the above annotations for a class for auto-detection but different types are provided so that you can easily distinguish the purpose of the annotated classes.


What is DispatcherServlet and ContextLoaderListener?

什么是 DispatcherServlet 和 ContextLoaderListener?(zh_CN)

DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.
DispatcherServlet 是 Spring MVC 应用程序中的前端控制器,它加载 spring bean 配置文件并初始化所有配置的 bean。如果启用了注释,它还会扫描包并配置注释的任何 bean@Component, @Controller, @Repository 要么@Service 注释。(zh_CN)

ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.
ContextLoaderListener 是启动和关闭 Spring 根的监听器WebApplicationContext. 它的重要功能是结束生命周期ApplicationContext 到了生命周期ServletContext 并自动创建ApplicationContext. 我们可以使用它来定义可以在不同的 spring 上下文中使用的共享 bean。(zh_CN)


What is ViewResolver in Spring?

Spring 中的 ViewResolver 是什么?(zh_CN)

ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:
ViewResolver 实现用于按名称解析视图页面。通常我们在 spring bean 配置文件中配置它。例如:(zh_CN)

 <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">     <beans:property name="prefix" value="/WEB-INF/views/" />     <beans:property name="suffix" value=".jsp" /> </beans:bean>

InternalResourceViewResolver is one of the implementation of ViewResolver interface and we are providing the view pages directory and suffix location through the bean properties. So if a controller handler method returns “home”, view resolver will use view page located at /WEB-INF/views/home.jsp.
InternalResourceViewResolver 是其中一个实施ViewResolver 接口,我们通过 bean 属性提供视图页面目录和后缀位置。因此,如果控制器处理程序方法返回“home”,则视图解析程序将使用位于 / WEB-INF / views / home.jsp 的视图页面。(zh_CN)


What is a MultipartResolver and when its used?

什么是 MultipartResolver 以及何时使用?(zh_CN)

MultipartResolver interface is used for uploading files – CommonsMultipartResolver and StandardServletMultipartResolver are two implementations provided by spring framework for file uploading. By default there are no multipart resolvers configured but to use them for uploading files, all we need to define a bean named “multipartResolver” with type as MultipartResolver in spring bean configurations.
MultipartResolver 界面用于上传文件 - CommonsMultipartResolverStandardServletMultipartResolver 是 spring 框架提供的两种实现文件上传。默认情况下,没有配置多部分解析器但是要使用它们来上传文件,我们需要在 spring bean 配置中定义一个名为“multipartResolver”的 bean,其类型为 MultipartResolver。(zh_CN)

Once configured, any multipart request will be resolved by the configured MultipartResolver and pass on a wrapped HttpServletRequest. Then it’s used in the controller class to get the file and process it. For a complete example, please read Spring MVC File Upload Example.
配置完成后,任何多部分请求都将由配置的 MultipartResolver 解析并传递一个包装好的 HttpServletRequest。然后在控制器类中使用它来获取文件并对其进行处理。有关完整示例,请阅读[Spring MVC 文件上载示例](。(zh_CN)


How to handle exceptions in Spring MVC Framework?

如何处理 Spring MVC Framework 中的异常?(zh_CN)

Spring MVC Framework provides following ways to help us achieving robust exception handling.
Spring MVC Framework 提供了以下方法来帮助我们实现强大的异常处理。(zh_CN)

  1. Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
  2. 基于控制器 - 我们可以在控制器类中定义异常处理程序方法。我们所需要的只是使用@ExceptionHandler 注释来注释这些方法。(zh_CN)
  3. Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
  4. 全局异常处理程序 - 异常处理是一个跨领域的问题,Spring 提供了@ControllerAdvice 注释,我们可以使用它来定义我们的全局异常处理程序。(zh_CN)
  5. HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.
  6. HandlerExceptionResolver 实现 - 对于一般异常,大多数时候我们提供静态页面。 Spring Framework 提供HandlerExceptionResolver 我们可以实现的接口来创建全局异常处理程序。这种额外定义全局异常处理程序的原因是 Spring 框架还提供了我们可以在 spring bean 配置文件中定义的默认实现类,以获得 spring 框架异常处理的好处。(zh_CN)

For a complete example, please read Spring Exception Handling Example.
有关完整示例,请阅读[Spring 异常处理示例](。(zh_CN)


How to create ApplicationContext in a Java Program?

如何在 Java 程序中创建 ApplicationContext?(zh_CN)

There are following ways to create spring context in a standalone java program.
有以下方法可以在独立的 Java 程序中创建 spring 上下文。(zh_CN)

  1. AnnotationConfigApplicationContext: If we are using Spring in standalone java applications and using annotations for Configuration, then we can use this to initialize the container and get the bean objects.
  2. AnnotationConfigApplicationContext :如果我们在独立的 Java 应用程序中使用 Spring 并使用 Configuration 的注释,那么我们可以使用它来初始化容器并获取 bean 对象。(zh_CN)
  3. ClassPathXmlApplicationContext: If we have spring bean configuration xml file in standalone application, then we can use this class to load the file and get the container object.
  4. ClassPathXmlApplicationContext :如果我们在独立应用程序中有 spring bean 配置 xml 文件,那么我们可以使用这个类来加载文件并获取容器对象。(zh_CN)
  5. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
  6. FileSystemXmlApplicationContext :这类似于 ClassPathXmlApplicationContext,除了可以从文件系统中的任何位置加载 xml 配置文件。(zh_CN)


Can we have multiple Spring configuration files?

我们可以有多个 Spring 配置文件吗?(zh_CN)

For Spring MVC applications, we can define multiple spring context configuration files through contextConfigLocation. This location string can consist of multiple locations separated by any number of commas and spaces. For example;
对于 Spring MVC 应用程序,我们可以通过定义多个 spring 上下文配置文件contextConfigLocation. 此位置字符串可以包含由任意数量的逗号和空格分隔的多个位置。例如;(zh_CN)

 <servlet>     <servlet-name>appServlet</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>     <init-param>             <param-name>contextConfigLocation</param-name>         <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,/WEB-INF/spring/appServlet/servlet-jdbc.xml</param-value>     </init-param>     <load-on-startup>1</load-on-startup> </servlet>

We can also define multiple root level spring configurations and load it through context-param. For example;
我们还可以定义多个根级弹簧配置并通过 context-param 加载它。例如;(zh_CN)

 <context-param>     <param-name>contextConfigLocation</param-name>     <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/root-security.xml</param-value> </context-param>

Another option is to use import element in the context configuration file to import other configurations, for example:
另一个选项是在上下文配置文件中使用 import 元素来导入其他配置,例如:(zh_CN)

 <beans:import resource="spring-jdbc.xml"/>


What is ContextLoaderListener?

什么是 ContextLoaderListener?(zh_CN)

ContextLoaderListener is the listener class used to load root context and define spring bean configurations that will be visible to all other contexts. It’s configured in web.xml file as:
ContextLoaderListener 是用于加载根上下文并定义将对所有其他上下文可见的 spring bean 配置的侦听器类。它在 web.xml 文件中配置为:(zh_CN)

 <context-param>     <param-name>contextConfigLocation</param-name>     <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param>      <listener>     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>


What are the minimum configurations needed to create Spring MVC application?

创建 Spring MVC 应用程序所需的最低配置是什么?(zh_CN)

For creating a simple Spring MVC application, we would need to do following tasks.
要创建一个简单的 Spring MVC 应用程序,我们需要执行以下任务。(zh_CN)

  • Add spring-context and spring-webmvc dependencies in the project.
  • spring-contextspring-webmvc 项目中的依赖项。(zh_CN)
  • Configure DispatcherServlet in the web.xml file to handle requests through spring container.
  • 配置DispatcherServlet 在 web.xml 文件中通过 spring 容器处理请求。(zh_CN)
  • Spring bean configuration file to define beans, if using annotations then it has to be configured here. Also we need to configure view resolver for view pages.
  • 用于定义 bean 的 Spring bean 配置文件,如果使用注释,则必须在此处进行配置。我们还需要为视图页面配置视图解析器。(zh_CN)
  • Controller class with request mappings defined to handle the client requests.
  • 控制器类,其中定义了请求映射以处理客户端请求。(zh_CN)

Above steps should be enough to create a simple Spring MVC Hello World application.
上面的步骤应该足以创建一个简单的 Spring MVC Hello World 应用程序。(zh_CN)


How would you relate Spring MVC Framework to MVC architecture?

您如何将 Spring MVC Framework 与 MVC 架构联系起来?(zh_CN)

As the name suggests Spring MVC is built on top of Model-View-Controller architecture. DispatcherServlet is the Front Controller in the Spring MVC application that takes care of all the incoming requests and delegate it to different controller handler methods.
顾名思义,Spring MVC 建立在 Model-View-Controller 架构之上。DispatcherServlet 是 Spring MVC 应用程序中的 Front Controller,负责处理所有传入的请求并将其委托给不同的控制器处理程序方法。(zh_CN)

Model can be any Java Bean in the Spring Framework, just like any other MVC framework Spring provides automatic binding of form data to java beans. We can set model beans as attributes to be used in the view pages.
Model 可以是 Spring Framework 中的任何 Java Bean,就像任何其他 MVC 框架一样,Spring 提供表单数据到 java bean 的自动绑定。我们可以将模型 bean 设置为要在视图页面中使用的属性。(zh_CN)

View Pages can be JSP, static HTMLs etc. and view resolvers are responsible for finding the correct view page. Once the view page is identified, control is given back to the DispatcherServlet controller. DispatcherServlet is responsible for rendering the view and returning the final response to the client.
查看页面可以是 JSP,静态 HTML 等,视图解析器负责查找正确的视图页面。一旦识别出视图页面,就会将控制权返回给 DispatcherServlet 控制器。 DispatcherServlet 负责呈现视图并将最终响应返回给客户端。(zh_CN)


How to achieve localization in Spring MVC applications?

如何在 Spring MVC 应用程序中实现本地化?(zh_CN)

Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:
Spring 通过资源包为本地化或 i18n 提供了出色的支持。使我们的应用程序本地化所需的基础步骤是:(zh_CN)

  1. Creating message resource bundles for different locales, such as, etc.
  2. 为不同的语言环境创建消息资源包,例如, 等。(zh_CN)
  3. Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
  4. 在类型的 spring bean 配置文件中定义 messageSource beanResourceBundleMessageSource 要么ReloadableResourceBundleMessageSource.(zh_CN)
  5. For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. Example configuration can be like below:
  6. 要更改语言环境支持,请定义 CookieLocaleResolver 类型的 localeResolver bean 并配置 LocaleChangeInterceptor 拦截器。示例配置如下所示:(zh_CN)

    <beans:bean id=”messageSource” class=””> <beans:property name=”basename” value=”classpath:messages” /> <beans:property name=”defaultEncoding” value=”UTF-8” /> </beans:bean> <beans:bean id=”localeResolver” class=”org.springframework.web.servlet.i18n.CookieLocaleResolver”> <beans:property name=”defaultLocale” value=”en” /> <beans:property name=”cookieName” value=”myAppLocaleCookie”></beans:property> <beans:property name=”cookieMaxAge” value=”3600”></beans:property> </beans:bean><beans:bean class=”org.springframework.web.servlet.i18n.LocaleChangeInterceptor”> <beans:property name=”paramName” value=”locale” /> </beans:bean>

  7. Use spring:message element in the view pages with key names, DispatcherServlet picks the corresponding value and renders the page in corresponding locale and return as response.

  8. 使用spring:message 在具有键名称的视图页面中,DispatcherServlet 选择相应的值并在相应的语言环境中呈现页面并作为响应返回。(zh_CN)

For a complete example, please read Spring Localization Example.
有关完整示例,请阅读[Spring Localization Example](。(zh_CN)


How can we use Spring to create Restful Web Service returning JSON response?

我们如何使用 Spring 创建 Restful Web Service 返回 JSON 响应?(zh_CN)

We can use Spring Framework to create Restful web services that returns JSON data. Spring provides integration with Jackson JSON API that we can use to send JSON response in restful web service.
我们可以使用 Spring Framework 创建返回 JSON 数据的 Restful Web 服务。 Spring 提供了与[Jackson JSON](的集成,我们可以使用它在宁静的Web服务中发送JSON响应。(zh_CN)

We would need to do following steps to configure our Spring MVC application to send JSON response:
我们需要执行以下步骤来配置 Spring MVC 应用程序以发送 JSON 响应:(zh_CN)

  1. Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:
  2. 添加[Jackson](依赖项,如果您使用的是Maven,可以使用以下代码完成:(zh_CN)



  3. Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:

  4. 配置RequestMappingHandlerAdapter bean 在 spring bean 配置文件中并将 messageConverters 属性设置为 MappingJackson2HttpMessageConverter bean。示例配置将是:(zh_CN)


    <beans:bean class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”> <beans:property name=”messageConverters”> beans:list <beans:ref bean=”jsonMessageConverter”/> </beans:list> </beans:property> </beans:bean> <beans:bean id=”jsonMessageConverter” class=”org.springframework.http.converter.json.MappingJackson2HttpMessageConverter”> </beans:bean>

  5. In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:

  6. 在控制器处理程序方法中,使用返回 Object 作为响应@ResponseBody 注解。示例代码:(zh_CN)

    @RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET) public @ResponseBody Employee getEmployee(@PathVariable(“id”) int empId) {“Start getEmployee. ID=”+empId); return empData.get(empId); }

  7. You can invoke the rest service through any API, but if you want to use Spring then we can easily do it using RestTemplate class.

  8. 您可以通过任何 API 调用其余服务,但是如果您想使用 Spring,那么我们可以使用 RestTemplate 类轻松地完成它。(zh_CN)

For a complete example, please read Spring Restful Webservice Example.
有关完整示例,请阅读[Spring Restful Webservice 示例](。(zh_CN)


What are some of the important Spring annotations you have used?

您使用过的一些重要的 Spring 注释是什么?(zh_CN)

Some of the Spring annotations that I have used in my project are:
我在项目中使用的一些 Spring 注释是:(zh_CN)

  • @Controller – for controller classes in Spring MVC project.
  • @控制器 - 用于 Spring MVC 项目中的控制器类。(zh_CN)
  • @RequestMapping – for configuring URI mapping in controller handler methods. This is a very important annotation, so you should go through Spring MVC RequestMapping Annotation Examples
  • @RequestMapping - 用于在控制器处理程序方法中配置 URI 映射。这是一个非常重要的注释,所以你应该通过[Spring MVC RequestMapping Annotation examples](
  • @ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
  • @ResponseBody - 用于发送 Object 作为响应,通常用于发送 XML 或 JSON 数据作为响应。(zh_CN)
  • @PathVariable – for mapping dynamic values from the URI to handler method arguments.
  • @PathVariable - 用于将动态值从 URI 映射到处理程序方法参数。(zh_CN)
  • @Autowired – for autowiring dependencies in spring beans.
  • @自动装配 - 用于在 spring bean 中自动连接依赖项。(zh_CN)
  • @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
  • @限定符 - 使用@Autowired 注释以避免在存在多个 bean 类型实例时出现混淆。(zh_CN)
  • @Service – for service classes.
  • @服务 - 用于服务类。(zh_CN)
  • @Scope – for configuring scope of the spring bean.
  • @范围 - 用于配置 spring bean 的范围。(zh_CN)
  • @Configuration, @ComponentScan and @Bean – for java based configurations.
  • @配置 @ ComponentScan @ Bean - 用于基于 java 的配置。(zh_CN)
  • AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc.
  • 用于配置方面和建议的 AspectJ 注释, @ Aspect @ Before @ After @ Around @ Pointcut 等(zh_CN)


Can we send an Object as the response of Controller handler method?

我们可以发送一个 Object 作为 Controller 处理程序方法的响应吗?(zh_CN)

Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.
是的,我们可以使用 @ ResponseBody 注释。这就是我们在 restful Web 服务中发送基于 JSON 或 XML 的响应的方式。(zh_CN)


How to upload file in Spring MVC Application?

如何在 Spring MVC Application 中上传文件?(zh_CN)

Spring provides built-in support for uploading files through MultipartResolver interface implementations. It’s very easy to use and requires only configuration changes to get it working. Obviously we would need to write controller handler method to handle the incoming file and process it. For a complete example, please refer Spring File Upload Example.
Spring 通过 MultipartResolver 接口实现为上传文件提供内置支持。它非常易于使用,只需要更改配置即可使其正常工作。显然,我们需要编写控制器处理程序方法来处理传入的文件并对其进行处理。有关完整示例,请参阅[Spring File Upload Example](。(zh_CN)


How to validate form data in Spring Web MVC Framework?

如何在 Spring Web MVC Framework 中验证表单数据?(zh_CN)

Spring supports JSR-303 annotation based validations as well as provide Validator interface that we can implement to create our own custom validator. For using JSR-303 based validation, we need to annotate bean variables with the required validations.
Spring 支持基于 JSR-303 注释的验证,并提供我们可以实现的 Validator 接口来创建我们自己的自定义验证器。对于使用基于 JSR-303 的验证,我们需要使用所需的验证来注释 bean 变量。(zh_CN)

For custom validator implementation, we need to configure it in the controller class. For a complete example, please read Spring MVC Form Validation Example.
对于自定义验证器实现,我们需要在控制器类中进行配置。有关完整示例,请阅读[Spring MVC 表单验证示例](。(zh_CN)


What is Spring MVC Interceptor and how to use it?

什么是 Spring MVC Interceptor 以及如何使用它?(zh_CN)

Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandle and afterCompletion.
Spring MVC 拦截器就像 Servlet 过滤器,允许我们拦截客户端请求并对其进行处理。我们可以在三个地方拦截客户请求 - preHandle postHandle afterCompletion 。(zh_CN)

We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
我们可以通过实现 HandlerInterceptor 接口或扩展抽象类 HandlerInterceptorAdapter 来创建 spring 拦截器。(zh_CN)

We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too. For a detailed example, please refer Spring MVC Interceptor Example.
我们需要在 spring bean 配置文件中配置拦截器。我们可以定义拦截器来拦截所有客户端请求,或者我们也可以为特定的 URI 映射配置拦截器。有关详细示例,请参阅[Spring MVC Interceptor 示例](。(zh_CN)


What is Spring JdbcTemplate class and how to use it?

什么是 Spring JdbcTemplate 类以及如何使用它?(zh_CN)

Spring Framework provides excellent integration with JDBC API and provides JdbcTemplate utility class that we can use to avoid bolier-plate code from our database operations logic such as Opening/Closing Connection, ResultSet, PreparedStatement etc.
Spring Framework 提供了与 JDBC API 的出色集成,并提供了 JdbcTemplate 实用程序类,我们可以使用它来避免来自我们的数据库操作逻辑的 bolier-plate 代码,例如 Opening / Closing Connection,ResultSet,PreparedStatement 等。(zh_CN)

For JdbcTemplate example, please refer Spring JDBC Example.
有关 JdbcTemplate 示例,请参阅[Spring JDBC 示例](。(zh_CN)


How to use Tomcat JNDI DataSource in Spring Web Application?

如何在 Spring Web 应用程序中使用 Tomcat JNDI DataSource?(zh_CN)

For using servlet container configured JNDI DataSource, we need to configure it in the spring bean configuration file and then inject it to spring beans as dependencies. Then we can use it with JdbcTemplate to perform database operations.
为了使用 servlet 容器配置的 JNDI DataSource,我们需要在 spring bean 配置文件中配置它,然后将它作为依赖项注入 spring bean。然后我们可以用它JdbcTemplate 执行数据库操作。(zh_CN)

Sample configuration would be:

 <beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">     <beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/> </beans:bean>

For complete example, please refer Spring Tomcat JNDI Example.
有关完整示例,请参阅[Spring Tomcat JNDI 示例](。(zh_CN)


How would you achieve Transaction Management in Spring?

您如何在 Spring 中实现事务管理?(zh_CN)

Spring framework provides transaction management support through Declarative Transaction Management as well as programmatic transaction management. Declarative transaction management is most widely used because it’s easy to use and works in most of the cases.
Spring 框架通过声明式事务管理以及程序化事务管理提供事务管理支持。声明式事务管理是最广泛使用的,因为它易于使用并且在大多数情况下都有效。(zh_CN)

We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure transaction manager for the DataSource in the spring bean configuration file.
我们使用注释方法@Transactional 声明式事务管理的注释。我们需要在 spring bean 配置文件中为 DataSource 配置事务管理器。(zh_CN)

 <bean id="transactionManager"     class="org.springframework.jdbc.datasource.DataSourceTransactionManager">     <property name="dataSource" ref="dataSource" /> </bean>


What is Spring DAO?

什么是春天 DAO?(zh_CN)

Spring DAO support is provided to work with data access technologies like JDBC, Hibernate in a consistent and easy way. For example we have JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupport and JpaDaoSupport for respective technologies.
提供 Spring DAO 支持以一致且简单的方式使用 JDBC,Hibernate 等数据访问技术。例如,我们有JdbcDaoSupport, HibernateDaoSupport, JdoDaoSupportJpaDaoSupport 各种技术。(zh_CN)

Spring DAO also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.
Spring DAO 还提供异常层次结构的一致性,我们不需要捕获特定的异常。(zh_CN)


How to integrate Spring and Hibernate Frameworks?

如何集成 Spring 和 Hibernate 框架?(zh_CN)

We can use Spring ORM module to integrate Spring and Hibernate frameworks, if you are using Hibernate 3+ where SessionFactory provides current session, then you should avoid using HibernateTemplate or HibernateDaoSupport classes and better to use DAO pattern with dependency injection for the integration.
我们可以使用 Spring ORM 模块来集成 Spring 和 Hibernate 框架,如果你使用 Hibernate 3+,其中 SessionFactory 提供当前会话,那么你应该避免使用HibernateTemplate 要么HibernateDaoSupport 类和更好地使用 DAO 模式和依赖注入进行集成。(zh_CN)

Also Spring ORM provides support for using Spring declarative transaction management, so you should utilize that rather than going for hibernate boiler-plate code for transaction management.
此外,Spring ORM 还支持使用 Spring 声明式事务管理,因此您应该使用它而不是使用 hibernate 样板代码进行事务管理。(zh_CN)

For better understanding you should go through following tutorials:


What is Spring Security?

什么是 Spring Security?(zh_CN)

Spring security framework focuses on providing both authentication and authorization in java applications. It also takes care of most of the common security vulnerabilities such as CSRF attack.
Spring 安全框架侧重于在 Java 应用程序中提供身份验证和授权。它还会处理大多数常见的安全漏洞,例如 CSRF 攻击。(zh_CN)

It’s very beneficial and easy to use Spring security in web applications, through the use of annotations such as @EnableWebSecurity. You should go through following posts to learn how to use Spring Security framework.
通过使用诸如的注释,在 Web 应用程序中使用 Spring 安全性非常有用且易于使用@EnableWebSecurity. 您应该通过以下帖子来了解如何使用 Spring Security 框架。(zh_CN)


How to inject a java.util.Properties into a Spring Bean?

如何将 java.util.Properties 注入 Spring Bean?(zh_CN)

We need to define propertyConfigurer bean that will load the properties from the given property file. Then we can use Spring EL support to inject properties into other bean dependencies. For example;
我们需要定义 propertyConfigurer bean,它将从给定的属性文件加载属性。然后我们可以使用 Spring EL 支持将属性注入其他 bean 依赖项。例如;(zh_CN)

 <bean id="propertyConfigurer"    class="">     <property name="location" value="/WEB-INF/" /> </bean>   <bean class="com.journaldev.spring.EmployeeDaoImpl">     <property name="maxReadResults" value="${}"/> </bean>

If you are using annotation to configure the spring bean, then you can inject property like below.
如果您使用注释来配置 spring bean,那么您可以注入如下所示的属性。(zh_CN)

 @Value("${maxReadResults}")  private int maxReadResults;


Name some of the design patterns used in Spring Framework?

列举 Spring Framework 中使用的一些设计模式?(zh_CN)

Spring Framework is using a lot of design patterns, some of the common ones are:
Spring Framework 使用了很多设计模式,其中一些常见的是:(zh_CN)

  1. Singleton Pattern: Creating beans with default scope.
  2. 单例模式:创建具有默认范围的 bean。(zh_CN)
  3. Factory Pattern: Bean Factory classes
  4. [工厂模式](工厂类(zh_CN)
  5. Prototype Pattern: Bean scopes
  6. [原型模式](范围(zh_CN)
  7. Adapter Pattern: Spring Web and Spring MVC
  8. [适配器模式]( Web 和 Spring MVC(zh_CN)
  9. Proxy Pattern: Spring Aspect Oriented Programming support
  10. [代理模式](面向方面编程支持(zh_CN)
  11. Template Method Pattern: JdbcTemplate, HibernateTemplate etc
  12. [模板方法模式](,HibernateTemplate等(zh_CN)
  13. Front Controller: Spring MVC DispatcherServlet
  14. Data Access Object: Spring DAO support
  15. 数据访问对象:Spring DAO 支持(zh_CN)
  16. Dependency Injection and Aspect Oriented Programming
  17. 依赖注入和面向方面编程(zh_CN)


What are some of the best practices for Spring Framework?

Spring Framework 有哪些最佳实践?(zh_CN)

Some of the best practices for Spring Framework are:
Spring Framework 的一些最佳实践是:(zh_CN)

  1. Avoid version numbers in schema reference, to make sure we have the latest configs.
  2. 避免模 ​​ 式参考中的版本号,以确保我们有最新的配置。(zh_CN)
  3. Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
  4. 根据 spring-jdbc.xml,spring-security.xml 等问题划分 spring bean 配置。(zh_CN)
  5. For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
  6. 对于在 Spring MVC 中的多个上下文中使用的 spring bean,在根上下文中创建它们并使用 listener 初始化。(zh_CN)
  7. Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
  8. 尽可能配置 bean 依赖关系,尽量避免自动装配。(zh_CN)
  9. For application level properties, best approach is to create a property file and read it in the spring bean configuration file.
  10. 对于应用程序级属性,最好的方法是创建属性文件并在 spring bean 配置文件中读取它。(zh_CN)
  11. For smaller applications, annotations are useful but for larger applications annotations can become a pain. If we have all the configuration in xml files, maintaining it will be easier.
  12. 对于较小的应用程序,注释很有用,但对于较大的应用程序,注释可能会变得很麻烦。如果我们在 xml 文件中拥有所有配置,那么维护它将更容易。(zh_CN)
  13. Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
  14. 对组件使用正确的注释可以轻松理解目的。对于服务,使用@Service 和 DAO bean 使用@Repository。(zh_CN)
  15. Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that gets usually added when you create projects through Spring Tool Suite templates.
  16. Spring 框架有很多模块,使用你需要的东西。删除通过 Spring Tool Suite 模板创建项目时通常添加的所有额外依赖项。(zh_CN)
  17. If you are using Aspects, make sure to keep the join pint as narrow as possible to avoid advice on unwanted methods. Consider custom annotations that are easier to use and avoid any issues.
  18. 如果您使用的是 Aspects,请确保尽可能缩小连接点,以避免对不需要的方法提出建议。考虑更易于使用的自定义注释并避免任何问题。(zh_CN)
  19. Use dependency injection when there is actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.
  20. 当有实际好处时使用依赖注入,仅仅为了松散耦合而不使用它因为它更难维护。(zh_CN)

That’s all for Spring Framework interview questions. I hope these questions will help you in coming Java EE interview. I will keep on adding more questions to the list as soon as I found them. If you know some more questions that should be part of the list, make sure to add a comment for it and I will include it.
这就是 Spring Framework 面试问题的全部内容。我希望这些问题可以帮助您进行 Java EE 访谈。我一发现就会在列表中继续添加更多问题。如果您知道应该成为列表一部分的更多问题,请确保为其添加注释,我将包含它。(zh_CN)