I have posted a lot of Spring Tutorials recently. This post will help you get through Spring interview Questions explaining the core concepts in detail.

我最近发布了很多Spring教程 。 这篇文章将帮助您完成Spring面试问题 ,详细解释核心概念。

Spring Framework is one of the most popular Java EE frameworks for web applications. Dependency Injection and Aspect Oriented Programming are at the heart of Spring framework. If you are good in Spring Framework, the chances of getting selected get high.

Spring框架是Web应用程序中最受欢迎的Java EE框架之一。 依赖注入面向方面的编程是Spring框架的核心。 如果您精通Spring Framework,那么被选中的机会就会增加。

Pro Tip: 专家提示 : Core Java is the base of any Java based framework, so if you are preparing for interviews then please go through Core Java是任何基于Java的框架的基础,因此,如果您准备面试,请阅读Core Java Interview Questions and Core Java面试问题和Java Interview Questions articles.Java面试问题文章。

Spring面试问题 (Spring Interview Questions)

  1. What is Spring Framework?什么是Spring Framework?
  2. What are some of the important features and advantages of Spring Framework?Spring Framework的重要特征和优点是什么?
  3. What do you understand by Dependency Injection?您对依赖注入有什么了解?
  4. How do we implement DI in Spring Framework?我们如何在Spring Framework中实现DI?
  5. What are the new features in Spring 5?Spring 5有哪些新功能?
  6. What is Spring WebFlux?什么是Spring WebFlux?
  7. What are the benefits of using Spring Tool Suite?使用Spring Tool Suite有什么好处?
  8. Name some of the important Spring Modules?命名一些重要的Spring模块?
  9. What do you understand by Aspect Oriented Programming?您对面向方面的编程有什么了解?
  10. What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?AOP中的方面,建议,切入点,JointPoint和建议参数是什么?
  11. What is the difference between Spring AOP and AspectJ AOP?Spring AOP和AspectJ AOP有什么区别?
  12. What is Spring IoC Container?什么是Spring IoC容器?
  13. What is a Spring Bean?什么是Spring Bean?
  14. What is the importance of Spring bean configuration file?Spring bean配置文件的重要性是什么?
  15. What are different ways to configure a class as Spring Bean?有什么不同的方法可以将类配置为Spring Bean?
  16. What are different scopes of Spring Bean?Spring Bean有哪些不同范围?
  17. What is Spring Bean life cycle?什么是Spring Bean生命周期?
  18. How to get ServletContext and ServletConfig object in a Spring Bean?如何在Spring Bean中获取ServletContext和ServletConfig对象?
  19. What is Bean wiring and @Autowired annotation?什么是Bean接线和@Autowired注释?
  20. What are different types of Spring Bean autowiring?有哪些不同类型的Spring Bean自动装配?
  21. Does Spring Bean provide thread safety?Spring Bean是否提供线程安全性?
  22. What is a Controller in Spring MVC?Spring MVC中的控制器是什么?
  23. What’s the difference between @Component, @Repository & @Service annotations in Spring?Spring中的@ Component,@ Repository和@Service批注有什么区别?
  24. What is DispatcherServlet and ContextLoaderListener?什么是DispatcherServlet和ContextLoaderListener?
  25. What is ViewResolver in Spring?Spring中的ViewResolver是什么?
  26. What is a MultipartResolver and when it’s used?什么是MultipartResolver?何时使用?
  27. How to handle exceptions in Spring MVC Framework?如何在Spring MVC Framework中处理异常?
  28. How to create ApplicationContext in a Java Program?如何在Java程序中创建ApplicationContext?
  29. Can we have multiple Spring configuration files?我们可以有多个Spring配置文件吗?
  30. What is ContextLoaderListener?什么是ContextLoaderListener?
  31. What are the minimum configurations needed to create Spring MVC application?创建Spring MVC应用程序所需的最低配置是什么?
  32. How would you relate Spring MVC Framework to MVC architecture?您如何将Spring MVC Framework与MVC架构联系起来?
  33. How to achieve localization in Spring MVC applications?如何在Spring MVC应用程序中实现本地化?
  34. How can we use Spring to create Restful Web Service returning JSON response?我们如何使用Spring创建返回JSON响应的Restful Web Service?
  35. What are some of the important Spring annotations you have used?您使用了哪些重要的Spring批注?
  36. Can we send an Object as the response of Controller handler method?我们可以发送一个对象作为Controller处理程序方法的响应吗?
  37. How to upload file in Spring MVC Application?如何在Spring MVC应用程序中上传文件?
  38. How to validate form data in Spring Web MVC Framework?如何在Spring Web MVC Framework中验证表单数据?
  39. What is Spring MVC Interceptor and how to use it?什么是Spring MVC拦截器以及如何使用?
  40. What is Spring JdbcTemplate class and how to use it?什么是Spring JdbcTemplate类以及如何使用它?
  41. How to use Tomcat JNDI DataSource in Spring Web Application?如何在Spring Web Application中使用Tomcat JNDI数据源?
  42. How would you achieve Transaction Management in Spring?您将如何在Spring实现事务管理?
  43. What is Spring DAO?什么是Spring DAO?
  44. How to integrate Spring and Hibernate Frameworks?如何集成Spring和Hibernate框架?
  45. What is Spring Security?什么是Spring Security?
  46. How to inject a java.util.Properties into a Spring Bean?如何将java.util.Properties注入Spring Bean?
  47. Name some of the design patterns used in Spring Framework?命名Spring框架中使用的一些设计模式?
  48. What are some of the best practices for Spring Framework?Spring框架有哪些最佳实践?

Spring面试问答 (Spring Interview Questions and Answers)

  1. 什么是Spring Framework? (What is Spring Framework?)

    Spring is one of the most widely used Java EE framework. Spring framework core concepts are “Dependency Injection” and “Aspect Oriented Programming”.

    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.

    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 the Spring framework is easy and fun at the same time.

    Recommended Read: Spring Framework

    Spring是使用最广泛的Java EE框架之一。 Spring框架的核心概念是“依赖注入”和“面向方面的编程”。

    Spring框架可以用于普通的Java应用程序中,还可以通过实现依赖注入来实现不同组件之间的松散耦合,并且我们可以使用Spring支持面向方面的编程来执行诸如日志记录和身份验证之类的跨领域任务。

    我喜欢spring,因为它为特定任务(例如Spring MVC和Spring JDBC)提供了许多功能和不同的模块。 由于它是一个包含大量在线资源和活跃社区成员的开源框架,因此与Spring框架一起工作既轻松又有趣。

    推荐阅读 : Spring Framework

  2. Spring Framework的重要特征和优点是什么? (What are some of the important features and advantages of Spring Framework?)

    Spring Framework is built on top of two design concepts – Dependency Injection and Aspect Oriented Programming.

    Some of the features of spring framework are:

    • Lightweight and very little overhead of using framework for our development.
    • 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 IoC container manages Spring Bean life cycle and project specific configurations such as JNDI lookup.
    • 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.
    • 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.

    Some of the advantages of using Spring Framework are:

    • 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.
    • 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.
    • 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.
    • 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 on our project.
    • 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 the different framework for different requirements.

    Spring框架建立在两个设计概念之上:依赖注入和面向方面的编程。

    Spring框架的一些功能包括:

    • 轻巧,使用框架进行开发的开销很小。
    • 依赖注入或控制反转以编写彼此独立的组件,spring容器负责将它们连接在一起以完成我们的工作。
    • Spring IoC容器管理Spring Bean生命周期和项目特定的配置,例如JNDI查找。
    • Spring MVC框架可用于创建Web应用程序以及能够返回XML和JSON响应的静态Web服务。
    • 通过注释或通过spring bean配置文件,只需很少的配置即可支持事务管理,JDBC操作,文件上传,异常处理等。

    使用Spring Framework的一些优点是:

    • 为了减少应用程序不同组件之间的直接依赖关系,通常Spring IoC容器负责初始化资源或bean,并将它们作为依赖关系注入。
    • 在Spring框架中编写单元测试用例很容易,因为我们的业务逻辑与实际的资源实现类没有直接的依赖关系。 我们可以轻松地编写测试配置,并为测试目的注入模拟豆。
    • 减少样板代码的数量,例如初始化对象,打开/关闭资源。 我非常喜欢JdbcTemplate类,因为它有助于我们删除JDBC编程附带的所有样板代码。
    • Spring框架分为几个模块,它有助于我们保持应用程序的轻量级。 例如,如果我们不需要Spring事务管理功能,则无需在项目中添加该依赖项。
    • Spring框架支持大多数Java EE功能,甚至更多。 它总是在新技术之上,例如,有一个Android的Spring项目可以帮助我们为原生Android应用程序编写更好的代码。 这使spring框架成为一个完整的程序包,我们不需要为不同的需求而照顾不同的框架。
  3. 您对依赖注入有什么了解? (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.

    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.

    依赖注入设计模式使我们可以删除硬编码的依赖,并使我们的应用程序松散耦合,可扩展和可维护。 我们可以实现依赖项注入模式,以将依赖项解决方案从编译时移至运行时。

    使用依赖注入的一些好处是关注点的分离,样板代码的减少,可配置的组件以及简单的单元测试。

    在Dependency Injection Tutorial中内容。 我们还可以使用Google Guice进行依赖项注入来自动化依赖项注入的过程。 但是在大多数情况下,我们不仅在寻求依赖注入,这就是为什么Spring是这样做的首选。

  4. 我们如何在Spring Framework中实现DI? (How do we implement DI in Spring Framework?)

    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 a sample project zip file, that you can download and play around to learn more.

    我们可以使用基于Spring XML以及基于注释的配置在Spring应用程序中实现DI。 为了更好地理解,请阅读Spring Dependency Injection示例,您可以在其中学习JUnit测试用例的两种方式。 该帖子还包含一个示例项目zip文件,您可以下载并试用该文件以了解更多信息。

  5. Spring 5有哪些新功能? (What are the new features in Spring 5?)

    Spring 5 brought a massive update to Spring framework. Some of the new features in Spring 5 are:

    1. Spring 5 runs on Java 8+ and supports Java EE 7. So we can use lambda expressions and Servlet 4.0 features. It’s good to see Spring trying to support the latest versions.
    2. Spring Framework 5.0 comes with its own Commons Logging bridge; spring-jcl instead of standard Commons Logging.
    3. Support for providing spring components information through index file “META-INF/spring.components” rather than classpath scanning.
    4. Spring WebFlux brings reactive programming to the Spring Framework.
    5. Spring 5 also supports Kotlin programming now. This is a huge step towards supporting functional programming, just as Java is also moving towards functional programming.
    6. Support for JUnit 5 and parallel testing execution in the Spring TestContext Framework.

    You can read about these features in more detail at Spring 5 Features.

    Spring 5对Spring框架进行了大规模更新。 Spring 5中的一些新功能包括:

    1. Spring 5在Java 8+上运行,并支持Java EE7。因此,我们可以使用lambda表达式和Servlet 4.0功能。 很高兴看到Spring尝试支持最新版本。
    2. Spring Framework 5.0带有自己的Commons Logging桥; 用spring-jcl代替标准的Commons Logging。
    3. 支持通过索引文件“ META-INF / spring.components”而不是类路径扫描来提供spring组件信息。
    4. Spring WebFlux将响应式编程引入了Spring框架。
    5. Spring 5现在也支持Kotlin编程。 正如Java也正在朝函数式编程迈进一样,这是朝着支持函数式编程迈出的一大步。
    6. 在Spring TestContext Framework中支持JUnit 5和并行测试执行。

    您可以在Spring 5 Features中更详细地了解这些功能。

  6. 什么是Spring WebFlux? (What is Spring WebFlux?)

    Spring WebFlux is the new module introduced in Spring 5. Spring WebFlux is the first step towards the reactive programming model in spring framework.

    Spring WebFlux is the alternative to the Spring MVC module. Spring WebFlux is used to create a fully asynchronous and non-blocking application built on the event-loop execution model.

    You can read more about it at Spring WebFlux Tutorial.

    Spring WebFlux是Spring 5中引入的新模块。SpringWebFlux是向Spring框架中的React式编程模型迈出的第一步。

    Spring WebFlux是Spring MVC模块的替代方案。 Spring WebFlux用于创建基于事件循环执行模型的完全异步且非阻塞的应用程序。

    您可以在Spring WebFlux教程中阅读有关它的更多信息。

  7. 使用Spring Tool Suite有什么好处? (What are the benefits of using Spring Tool Suite?)

    We can install plugins into Eclipse to get all the features of Spring Tool Suite. However, STS comes with Eclipse with some other important kinds of stuff such as Maven support, Templates for creating different types of Spring projects and tc server for better performance with Spring applications.

    I like STS because it highlights the Spring components and if you are using AOP pointcuts and advice, 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.

    我们可以将插件安装到Eclipse中,以获取Spring Tool Suite的所有功能。 但是,STS随Eclipse一起提供了其他一些重要的东西,例如Maven支持,用于创建不同类型的Spring项目的模板以及用于在Spring应用程序中获得更好性能的tc服务器。

    我喜欢STS,因为它突出显示了Spring组件,并且如果您使用的是AOP切入点和建议,那么它将清楚地显示特定切入点下的方法。 因此,我不想自己安装所有内容,而是在开发基于Spring的应用程序时使用STS。

  8. 命名一些重要的Spring模块? (Name some of the important Spring Modules?)

    Some of the important Spring Framework modules are:

    • Spring Context – for dependency injection.
    • Spring AOP – for aspect oriented programming.
    • Spring DAO – for database operations using DAO pattern
    • Spring JDBC – for JDBC and DataSource support.
    • Spring ORM – for ORM tools support such as Hibernate
    • Spring Web Module – for creating web applications.
    • Spring MVC – Model-View-Controller implementation for creating web applications, web services etc.

    一些重要的Spring Framework模块是:

    • Spring Context –用于依赖注入。
    • Spring AOP –用于面向方面的编程。
    • Spring DAO –使用DAO模式进行数据库操作
    • Spring JDBC –用于JDBC和DataSource支持。
    • Spring ORM –对ORM工具的支持,例如Hibernate
    • Spring Web Module –用于创建Web应用程序。
    • Spring MVC –用于创建Web应用程序,Web服务等的Model-View-Controller实现。
  9. 您对面向方面的编程有什么了解? (What do you understand by Aspect Oriented Programming?)

    Enterprise applications have some common cross-cutting concerns that are applicable to 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 takes out the direct dependency of cross-cutting tasks from classes that are 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应用程序中方面是通过Aspects实现的,它们被配置为跨越不同的类方法。

    AOP从普通的面向对象编程中无法获得的类中截取交叉任务的直接依赖关系。 例如,我们可以有一个单独的日志记录类,但是这些类又必须调用这些方法来记录数据。 在Spring AOP Example中阅读有关Spring AOP支持的更多信息。

  10. AOP中的方面,建议,切入点,JointPoint和建议参数是什么? (What is Aspect, Advice, Pointcut, JointPoint and Advice Arguments in AOP?)

    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.

    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.

    Pointcut: Pointcut are regular expressions that are 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.

    Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join point is always the execution of a method.

    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 the argument type is determined.

    These concepts seems confusing at first, but if you go through Spring Aspect, Advice Example then you can easily relate to them.

    Aspect :Aspect是实现诸如事务管理之类的跨领域关注点的类。 Aspects可以是配置后在Spring Bean配置文件中配置的普通类,或者我们可以使用Spring AspectJ支持使用@Aspect批注将类声明为Aspect。

    建议 :建议是针对特定连接点采取的操作。 就编程而言,它们是在应用程序中达到具有匹配切入点的特定连接点时执行的方法。 您可以将建议视为Spring拦截器或Servlet过滤器 。

    切入点 :切入点是与联接点匹配的正则表达式,用于确定是否需要执行建议。 Pointcut使用与联接点匹配的不同类型的表达式。 Spring框架使用AspectJ切入点表达语言来确定将在其中应用建议方法的连接点。

    连接点 :连接点是应用程序中的特定点,例如方法执行,异常处理,更改对象变量值等。在Spring AOP中,连接点始终是方法的执行。

    建议参数 :我们可以在建议方法中传递参数。 我们可以在切入点中使用args()表达式,以将其应用于与参数模式匹配的任何方法。 如果使用此选项,则需要在确定参数类型的地方的advice方法中使用相同的名称。

    这些概念乍一看似乎令人困惑,但是如果您通过Spring Aspect,咨询示例,那么您可以轻松地将它们联系起来。

  11. Spring AOP和AspectJ AOP有什么区别? (What is the difference between Spring AOP and AspectJ AOP?)

    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:

    • Spring AOP is simpler to use than AspectJ because we don’t need to worry about the weaving process.
    • Spring AOP supports AspectJ annotations, so if you are familiar with AspectJ then working with Spring AOP is easier.
    • Spring AOP supports only proxy-based AOP, so it can be applied only to method execution join points. AspectJ support all kinds of pointcuts.
    • One of the shortcomings of Spring AOP is that it can be applied only to the beans created through Spring Context.

    AspectJ是面向方面编程的行业标准实现,而Spring在某些情况下实现AOP。 Spring AOP和AspectJ之间的主要区别是:

    • Spring AOP比AspectJ更易于使用,因为我们无需担心编织过程。
    • Spring AOP支持AspectJ注释,因此,如果您熟悉AspectJ,那么使用Spring AOP会更容易。
    • Spring AOP仅支持基于代理的AOP,因此它只能应用于方法执行连接点。 AspectJ支持各种切入点。
    • Spring AOP的缺点之一是它只能应用于通过Spring Context创建的bean。
  12. 什么是Spring IoC容器? (What is Spring IoC Container?)

    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 makes it ready for our use.

    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.

    Some of the useful ApplicationContext implementations that we use are;

    • AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
    • ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
    • FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
    • AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.

    控制反转 (IoC)是一种实现对象依赖关系之间松散耦合的机制。 为了在运行时实现对象的松散耦合和动态绑定,这些对象定义了由其他汇编器对象注入的它们的依赖项。 Spring IoC容器是将依赖项注入到对象中并使其可供我们使用的程序。

    Spring Framework IoC容器类是org.springframework.beansorg.springframework.context包的一部分,并为我们提供了分离对象依赖关系的不同方法。

    我们使用的一些有用的ApplicationContext实现是:

    • AnnotationConfigApplicationContext :对于使用基于注释的配置的独立Java应用程序。
    • ClassPathXmlApplicationContext :对于使用基于XML的配置的独立Java应用程序。
    • FileSystemXmlApplicationContext :与ClassPathXmlApplicationContext相似,但可以从文件系统中的任何位置加载xml配置文件。
    • Web应用程序的AnnotationConfigWebApplicationContextXmlWebApplicationContext
  13. 什么是Spring Bean? (What is a Spring Bean?)

    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 container manages the life cycle of Spring Bean, bean scopes and injecting any required dependencies in the bean.

    由Spring IoC容器初始化的任何普通Java类都称为Spring Bean。 我们使用Spring ApplicationContext来获取Spring Bean实例。

    Spring IoC容器管理Spring Bean的生命周期,bean范围并在Bean中注入任何必需的依赖项。

  14. Spring bean配置文件的重要性是什么? (What is the importance of Spring bean configuration file?)

    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 initializes all of them. Once the context is initialized, we can use it to get different bean instances.

    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 Context初始化的bean。 当我们创建Spring ApplicationContext的实例时,它将读取spring bean XML文件并初始化所有这些文件。 一旦上下文被初始化,我们就可以使用它来获取不同的bean实例。

    除了Spring Bean配置之外,该文件还包含spring MVC拦截器,视图解析器和其他元素,以支持基于注释的配置。

  15. 有什么不同的方法可以将类配置为Spring Bean? (What are different ways to configure a class as Spring Bean?)

    There are three different ways to configure Spring Bean.

    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:

      <bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
    2. 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:

      To get this bean from spring context, we need to use following code snippet:

      AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfiguration.class);
      MyService service = ctx.getBean(MyService.class);
    3. 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:

    有三种不同的方法来配置Spring Bean。

    1. XML配置 :这是最流行的配置,我们可以在上下文文件中使用bean元素来配置Spring Bean。 例如:

      <bean name="myBean" class="com.journaldev.spring.beans.MyBean"></bean>
    2. 基于Java的配置 :如果仅使用批注,则可以使用@Bean批注配置Spring bean。 该注释与@Configuration类一起使用,以配置spring bean。 示例配置为:

      要从spring上下文中获取此bean,我们需要使用以下代码片段:

      AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfiguration.class);
      MyService service = ctx.getBean(MyService.class);
    3. 基于注释的配置 :我们还可以将@ Component,@ Service,@ Repository和@Controller注释与类一起使用,以将其配置为spring bean。 对于这些,我们需要提供基本程序包位置以扫描这些类。 例如:
  16. Spring Bean有哪些不同范围? (What are different scopes of Spring Bean?)

    There are five scopes defined for Spring Beans.

    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. prototype: A new instance will be created every time the bean is requested.
    3. 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.
    4. session: A new bean will be created for each HTTP session by the container.
    5. global-session: This is used to create global session beans for Portlet applications.

    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.

    To set spring bean scopes we can use “scope” attribute in bean element or @Scope annotation for annotation based configurations.

    Spring Bean定义了五个作用域。

    1. 单例 :将为每个容器创建一个bean实例。 这是spring bean的默认范围。 在使用此范围时,请确保spring bean没有共享的实例变量,否则可能会导致数据不一致问题,因为它不是线程安全的。
    2. prototype :每次请求bean时都会创建一个新实例。
    3. request :这与原型范围相同,但是它打算用于Web应用程序。 将为每个HTTP请求创建一个新的bean实例。
    4. session :容器将为每个HTTP会话创建一个新bean。
    5. global-session :用于为Portlet应用程序创建全局会话Bean。

    Spring框架是可扩展的,我们也可以创建自己的范围,但是大多数时候我们对框架提供的范围感到满意。

    要设置Spring bean的作用域,我们可以在bean元素中使用“ scope”属性,或者对基于注释的配置使用@Scope注释。

  17. 什么是Spring Bean生命周期? (What is Spring Bean life cycle?)

    Spring Beans are initialized by Spring Container and all the dependencies are also injected. When the 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.

    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.

    Spring Bean由Spring Container初始化,并且所有依赖项也被注入。 当上下文被销毁时,它也会销毁所有初始化的bean。 在大多数情况下,此方法效果很好,但有时我们想初始化其他资源或进行一些验证,以使我们的bean可以立即使用。 Spring框架为Spring bean中的初始化后和销毁前方法提供了支持。

    我们可以通过两种方式来做到这一点-通过实现InitializingBeanDisposableBean接口,或在Spring bean配置中使用init-methoddestroy-method属性。 有关更多详细信息,请阅读Spring Bean生命周期方法 。

  18. 如何在Spring Bean中获取ServletContext和ServletConfig对象? (How to get ServletContext and ServletConfig object in a Spring Bean?)

    There are two ways to get Container specific objects in the spring bean.

    1. Implementing Spring *Aware interfaces, for these ServletContextAware and ServletConfigAware interfaces, for complete example of these aware interfaces, please read Spring Aware Interfaces
    2. Using @Autowired annotation with bean variable of type ServletContext and ServletConfig. They will work only in servlet container specific environment only though.
      @Autowired
      ServletContext servletContext;

    有两种方法可以在Spring bean中获取Container特定的对象。

    1. 为这些ServletContextAware和ServletConfigAware接口实现Spring * Aware接口,有关这些感知接口的完整示例,请阅读Spring Aware接口
    2. @Autowired注释与ServletContextServletConfig类型的bean变量一起使用。 但是,它们仅在servlet容器特定的环境中才有效。
  19. 什么是Bean接线和@Autowired注释? (What is Bean wiring and @Autowired annotation?)

    The process of injection spring bean dependencies while initializing it called Spring Bean Wiring.

    Usually, it’s best practice to do the explicit wiring of all the bean dependencies, but the spring framework also supports auto-wiring. 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.

    For more details about @Autowired annotation, please read Spring Autowire Example.

    初始化时注入Spring bean依赖项的过程称为Spring Bean Wiring。

    通常,最佳做法是对所有bean依赖项进行显式接线,但是spring框架还支持自动接线。 我们可以将@Autowired注释与用于自动装配byType的字段或方法一起使用。 为了使该注释生效,我们还需要在spring bean配置文件中启用基于注释的配置。 这可以通过context:annotation-config元素来完成。

    有关@Autowired批注的更多详细信息,请阅读Spring Autowire Example 。

  20. 有哪些不同类型的Spring Bean自动装配? (What are different types of Spring Bean autowiring?)

    There are four types of autowiring in Spring framework.

    1. autowire byName
    2. autowire byType
    3. autowire by constructor
    4. autowiring by @Autowired and @Qualifier annotations

    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框架中有四种自动装配类型。

    1. 自动连线byName
    2. 自动接线
    3. 通过构造器自动装配
    4. 通过@Autowired@Qualifier注释自动布线

    在Spring 3.1之前,还支持通过autodetect自动装配,类似于通过构造函数或byType自动装配。 有关这些选项的更多详细信息,请阅读Spring Bean Autowiring 。

  21. Spring Bean是否提供线程安全性? (Does Spring Bean provide thread safety?)

    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.

    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的默认范围是单例,因此每个上下文只有一个实例。 这意味着所有具有任何线程可以更新的类级别变量的变量都将导致数据不一致。 因此,在默认模式下,spring bean不是线程安全的。

    但是,我们可以将spring bean的作用域更改为请求,原型或会话,从而以性能为代价实现线程安全。 这是设计决定,基于项目要求。

  22. Spring MVC中的控制器是什么? (What is a Controller in Spring MVC?)

    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.

    A Controller class is responsible to handle a 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.

    就像MVC设计模式一样,Controller是处理所有客户端请求并将其发送到配置的资源以进行处理的类。 在Spring MVC中, org.springframework.web.servlet.DispatcherServlet是前端控制器类,用于根据Spring Bean配置初始化上下文。

    Controller类负责根据请求映射处理其他类型的客户端请求。 我们可以使用@Controller注释创建一个控制器类。 通常,它与@RequestMapping批注一起使用,以定义特定URI映射的处理程序方法。

  23. Spring中的@ Component,@ Controller,@ Repository和@Service批注有什么区别? (What’s the difference between @Component, @Controller, @Repository & @Service annotations in Spring?)

    @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.

    @Controller is a specific type of component, used in MVC applications and mostly used with RequestMapping annotation.

    @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.

    @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.

    @Component用于指示类是组件。 这些类用于自动检测,并在使用基于注释的配置时配置为Bean。

    @Controller是一种特定类型的组件,在MVC应用程序中使用,并且通常与RequestMapping批注一起使用。

    @Repository批注用于指示组件用作存储库,以及用于存储/检索/搜索数据的机制。 我们可以将此注释与DAO模式实现类一起应用。

    @Service用于指示类是服务。 通常,为此提供一些提供服务的业务外观类。

    我们可以将以上任何注释用于一个类,以进行自动检测,但是提供了不同的类型,以便您可以轻松地区分注释的类的用途。

  24. 什么是DispatcherServlet和ContextLoaderListener? (What is DispatcherServlet and ContextLoaderListener?)

    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.

    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.

    DispatcherServlet是Spring MVC应用程序中的前端控制器,它加载Spring bean配置文件并初始化所有已配置的bean。 如果启用了注释,则它还将扫描软件包并配置任何使用@Component @Controller@Repository @Controller@Repository@Service注释进行注释的bean。

    ContextLoaderListener是用于启动和关闭Spring根WebApplicationContext的侦听器。 它的重要功能是生命周期占用ApplicationContext到生命周期ServletContext和自动创建ApplicationContext 。 我们可以使用它来定义可以在不同的Spring上下文中使用的共享bean。

  25. Spring中的ViewResolver是什么? (What is ViewResolver in Spring?)

    ViewResolver implementations are used to resolve the view pages by name. Usually we configure it in the spring bean configuration file. For example:

    <!-- 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.

    ViewResolver实现用于按名称解析视图页面。 通常我们在spring bean配置文件中配置它。 例如:

    InternalResourceViewResolverViewResolver界面的实现之一,我们通过bean属性提供视图页面目录和后缀位置。 因此,如果控制器处理程序方法返回“ home”,则视图解析器将使用位于/WEB-INF/views/home.jsp的视图页面。

  26. 什么是MultipartResolver?何时使用? (What is a MultipartResolver and when it’s used?)

    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.

    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接口用于上传文件– CommonsMultipartResolverStandardServletMultipartResolver是spring框架提供的用于文件上传的两个实现。 默认情况下,没有配置多部分解析器,但是要使用它们来上传文件,我们需要在Spring bean配置中定义一个名为“ multipartResolver”的bean,其类型为MultipartResolver。

    一旦配置,任何多部分请求都将由配置的MultipartResolver解析,并传递一个包装好的HttpServletRequest。 然后在控制器类中使用它来获取文件并对其进行处理。 有关完整的示例,请阅读Spring MVC File Upload Example 。

  27. 如何在Spring MVC Framework中处理异常? (How to handle exceptions in Spring MVC Framework?)

    Spring MVC Framework provides the following ways to help us achieving robust exception handling.

    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. 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.
    3. 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.

    For a complete example, please read Spring Exception Handling Example.

    Spring MVC Framework提供了以下方法来帮助我们实现可靠的异常处理。

    1. 基于控制器 –我们可以在控制器类中定义异常处理程序方法。 我们需要的是使用@ExceptionHandler注释对这些方法进行注释。
    2. 全局异常处理程序 –异常处理是一个跨领域的问题,Spring提供了@ControllerAdvice批注,我们可以将其与任何类一起使用以定义我们的全局异常处理程序。
    3. HandlerExceptionResolver实现 –对于一般的异常,大多数时候我们提供静态页面。 Spring Framework提供了HandlerExceptionResolver接口,我们可以实现HandlerExceptionResolver接口来创建全局异常处理程序。 这种定义全局异常处理程序的其他方法背后的原因是,Spring框架还提供了默认实现类,我们可以在我们的Spring bean配置文件中定义这些默认实现类,以获得Spring框架异常处理的好处。

    有关完整的示例,请阅读Spring Exception Handling Example 。

  28. 如何在Java程序中创建ApplicationContext? (How to create ApplicationContext in a Java Program?)

    There are following ways to create spring context in a standalone java program.

    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. 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.
    3. FileSystemXmlApplicationContext: This is similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.

    有以下几种方法可以在独立的Java程序中创建spring上下文。

    1. AnnotationConfigApplicationContext :如果我们在独立的Java应用程序中使用Spring并为Configuration使用注释,则可以使用它来初始化容器并获取Bean对象。
    2. ClassPathXmlApplicationContext :如果在独立应用程序中有spring bean配置xml文件,则可以使用此类加载文件并获取容器对象。
    3. FileSystemXmlApplicationContext :这类似于ClassPathXmlApplicationContext,不同之处在于可以从文件系统中的任何位置加载xml配置文件。
  29. 我们可以有多个Spring配置文件吗? (Can we have multiple Spring configuration files?)

    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;

    <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;

    Another option is to use import element in the context configuration file to import other configurations, for example:

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

    对于Spring MVC应用程序,我们可以通过contextConfigLocation定义多个spring上下文配置文件。 此位置字符串可以包含多个位置,并用任意数量的逗号和空格分隔。 例如;

    我们还可以定义多个根级别的spring配置,并通过context-param加载它。 例如;

    <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>

    另一种选择是使用上下文配置文件中的import元素导入其他配置,例如:

  30. 什么是ContextLoaderListener? (What is ContextLoaderListener?)

    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:

    <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>

    ContextLoaderListener是用于加载根上下文并定义对所有其他上下文可见的spring bean配置的侦听器类。 在web.xml文件中将其配置为:

  31. 创建Spring MVC应用程序所需的最低配置是什么? (What are the minimum configurations needed to create Spring MVC application?)

    For creating a simple Spring MVC application, we would need to do the following tasks.

    • Add spring-context and spring-webmvc dependencies in the project.
    • Configure DispatcherServlet in the web.xml file to handle requests through spring container.
    • 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.
    • Controller class with request mappings defined to handle the client requests.

    为了创建一个简单的Spring MVC应用程序,我们需要执行以下任务。

    • 在项目中添加spring-contextspring-webmvc依赖项。
    • 在web.xml文件中配置DispatcherServlet以通过Spring容器处理请求。
    • 用于定义bean的Spring bean配置文件,如果使用注释,则必须在此处对其进行配置。 另外,我们需要为视图页面配置视图解析器。
    • 带有定义为处理客户端请求的请求映射的控制器类。
  32. Above steps should be enough to create a simple Spring MVC Hello World application.

    以上步骤足以创建一个简单的Spring MVC Hello World应用程序。

  33. 您如何将Spring MVC Framework与MVC架构联系起来? (How would you relate Spring MVC Framework to MVC architecture?)

    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.

    The 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.

    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.

    顾名思义,Spring MVC建立在“ 模型-视图-控制器”体系结构之上。 DispatcherServlet是Spring MVC应用程序中的前端控制器,负责处理所有传入请求并将其委托给不同的控制器处理程序方法。

    该模型可以是Spring框架中的任何Java Bean,就像Spring提供了将表单数据自动绑定到Java Bean的任何其他MVC框架一样。 我们可以将模型bean设置为要在视图页面中使用的属性。

    视图页面可以是JSP,静态HTML等。视图解析器负责查找正确的视图页面。 确定视图页面后,将控制权交还给DispatcherServlet控制器。 DispatcherServlet负责呈现视图并将最终响应返回给客户端。

  34. 如何在Spring MVC应用程序中实现本地化? (How to achieve localization in Spring MVC applications?)

    Spring provides excellent support for localization or i18n through resource bundles. Basis steps needed to make our application localized are:

    1. Creating message resource bundles for different locales, such as messages_en.properties, messages_fr.properties etc.
    2. Defining messageSource bean in the spring bean configuration file of type ResourceBundleMessageSource or ReloadableResourceBundleMessageSource.
    3. For change of locale support, define localeResolver bean of type CookieLocaleResolver and configure LocaleChangeInterceptor interceptor. Example configuration can be like below:
      <beans:bean id="messageSource"
      class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
      <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><interceptors><beans:bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"><beans:property name="paramName" value="locale" /></beans:bean>
      </interceptors>
    4. 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.

    For a complete example, please read Spring Localization Example.

    Spring通过资源包为本地化或i18n提供了出色的支持。 使我们的应用程序本地化所需的基本步骤为:

    1. 为不同的语言环境创建消息资源包,例如messages_en.properties,messages_fr.properties等。
    2. 在类型为ResourceBundleMessageSourceReloadableResourceBundleMessageSource的spring bean配置文件中定义messageSource bean。
    3. 要更改语言环境,请定义CookieLocaleResolver类型的localeResolver bean并配置LocaleChangeInterceptor拦截器。 配置示例如下所示:
    4. 在具有键名的视图页面中使用spring:message元素,DispatcherServlet选择相应的值,并在相应的语言环境中呈现该页面,并作为响应返回。

    有关完整示例,请阅读Spring Localization Example 。

  35. 我们如何使用Spring创建返回JSON响应的Restful Web Service? (How can we use Spring to create Restful Web Service returning JSON response?)

    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.

    We would need to do following steps to configure our Spring MVC application to send JSON response:

    1. Adding Jackson JSON dependencies, if you are using Maven it can be done with following code:

      <!-- Jackson -->
      <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>${jackson.databind-version}</version>
      </dependency>
    2. Configure RequestMappingHandlerAdapter bean in the spring bean configuration file and set the messageConverters property to MappingJackson2HttpMessageConverter bean. Sample configuration will be:
    3. In the controller handler methods, return the Object as response using @ResponseBody annotation. Sample code:
      @RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)
      public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {logger.info("Start getEmployee. ID="+empId);return empData.get(empId);
      }
    4. 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.

    For a complete example, please read Spring Restful Webservice Example.

    我们可以使用Spring框架创建返回JSON数据的Restful Web服务。 Spring提供了与Jackson JSON API的集成,我们可以使用它在静态Web服务中发送JSON响应。

    我们将需要执行以下步骤来配置Spring MVC应用程序以发送JSON响应:

    1. 添加Jackson JSON依赖项,如果您使用的是Maven,则可以使用以下代码完成:
    2. 在spring bean配置文件中配置RequestMappingHandlerAdapter bean,并将messageConverters属性设置为MappingJackson2HttpMessageConverter bean。 示例配置为:
      <!-- Configure to plugin JSON as request and response in method handler -->
      <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><!-- Configure bean to convert JSON to POJO and vice versa -->
      <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      </beans:bean>
    3. 在控制器处理程序方法中,使用@ResponseBody批注将Object作为响应返回。 样例代码:
    4. 您可以通过任何API调用rest服务,但是如果您想使用Spring,那么我们可以使用RestTemplate类轻松实现。

    有关完整的示例,请阅读Spring Restful Webservice Example 。

  36. 您使用了哪些重要的Spring批注? (What are some of the important Spring annotations you have used?)

    Some of the Spring annotations that I have used in my project are:

    • @Controller – for controller classes in Spring MVC project.
    • @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
    • @ResponseBody – for sending Object as response, usually for sending XML or JSON data as response.
    • @PathVariable – for mapping dynamic values from the URI to handler method arguments.
    • @Autowired – for autowiring dependencies in spring beans.
    • @Qualifier – with @Autowired annotation to avoid confusion when multiple instances of bean type is present.
    • @Service – for service classes.
    • @Scope – for configuring scope of the spring bean.
    • @Configuration, @ComponentScan and @Bean – for java based configurations.
    • AspectJ annotations for configuring aspects and advices, @Aspect, @Before, @After, @Around, @Pointcut etc.

    我在项目中使用的一些Spring注释是:

    • @Controller –用于Spring MVC项目中的控制器类。
    • @RequestMapping –用于在控制器处理程序方法中配置URI映射。 这是一个非常重要的注释,因此您应该阅读Spring MVC RequestMapping注释示例
    • @ResponseBody –用于发送对象作为响应,通常用于发送XML或JSON数据作为响应。
    • @PathVariable –用于将动态值从URI映射到处理程序方法参数。
    • @Autowired –用于自动装配Spring bean中的依赖项。
    • @Qualifier –带有@Autowired注释,以避免在存在多个bean类型的实例时造成混淆。
    • @Service –用于服务类。
    • @Scope –用于配置spring bean的范围。
    • @Configuration,@ComponentScan@Bean -基于Java的配置。
    • AspectJ的注解配置方面和建议,@Aspect,@Before,@After,@Around,@Pointcut等。
  37. 我们可以发送一个对象作为Controller处理程序方法的响应吗? (Can we send an Object as the response of Controller handler method?)

    Yes we can, using @ResponseBody annotation. This is how we send JSON or XML based response in restful web services.

    是的,我们可以使用@ResponseBody批注。 这就是我们在静态Web服务中发送基于JSON或XML的响应的方式。

  38. 如何在Spring MVC应用程序中上传文件? (How to upload file in Spring MVC Application?)

    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 。

  39. 如何在Spring Web MVC Framework中验证表单数据? (How to validate form data in Spring Web MVC Framework?)

    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.

    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支持基于JSR-303批注的验证,并提供Validator接口,我们可以使用该接口来创建自己的自定义验证器。 为了使用基于JSR-303的验证,我们需要使用必需的验证来注释bean变量。

    对于自定义验证器实现,我们需要在控制器类中对其进行配置。 有关完整的示例,请阅读Spring MVC表单验证示例 。

  40. 什么是Spring MVC拦截器以及如何使用? (What is Spring MVC Interceptor and how to use it?)

    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.

    We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.

    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 MVC拦截器就像Servlet过滤器一样,允许我们拦截客户端请求并对其进行处理。 我们可以在三个位置截获客户端请求– preHandlepostHandleafterCompletion

    我们可以通过实现HandlerInterceptor接口或扩展抽象类HandlerInterceptorAdapter来创建spring拦截器。

    我们需要在spring bean配置文件中配置拦截器。 我们可以定义一个拦截器来拦截所有客户端请求,也可以为特定的URI映射配置它。 有关详细示例,请参阅Spring MVC拦截器示例 。

  41. 什么是Spring JdbcTemplate类以及如何使用它? (What is Spring JdbcTemplate class and how to use it?)

    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.

    For JdbcTemplate example, please refer Spring JDBC Example.

    Spring Framework提供了与JDBC API的出色集成,并提供了JdbcTemplate实用程序类,我们可以使用它来避免数据库操作逻辑(如打开/关闭连接,ResultSet,PreparedStatement等)中的浮标代码。

    有关JdbcTemplate的示例,请参考Spring JDBC Example 。

  42. 如何在Spring Web Application中使用Tomcat JNDI数据源? (How to use Tomcat JNDI DataSource in Spring Web Application?)

    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.

    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.

    为了使用配置了JNDI数据源的servlet容器,我们需要在spring bean配置文件中对其进行配置,然后将其作为依赖项注入到spring bean中。 然后,我们可以将其与JdbcTemplate一起使用来执行数据库操作。

    示例配置为:

    有关完整的示例,请参考Spring Tomcat JNDI Example 。

  43. 您将如何在Spring实现事务管理? (How would you achieve Transaction Management in Spring?)

    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.

    We use annotate a method with @Transactional annotation for Declarative transaction management. We need to configure the transaction manager for the DataSource in the spring bean configuration file.

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

    Spring框架通过声明式事务管理以及程序性事务管理提供事务管理支持。 声明式事务管理使用最广泛,因为它易于使用并且在大多数情况下都可以使用。

    我们使用带有@Transactional批注的批注方法来进行声明式事务管理。 我们需要在spring bean配置文件中为DataSource配置事务管理器。

  44. 什么是Spring DAO? (What is Spring DAO?)

    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 also provides consistency in exception hierarchy and we don’t need to catch specific exceptions.

    提供了Spring DAO支持,以便以一致且简单的方式与JDBC,Hibernate等数据访问技术一起使用。 例如,我们具有针对各自技术的JdbcDaoSupportHibernateDaoSupportJdoDaoSupportJpaDaoSupport

    Spring DAO also provides consistency in exception hierarchy and we don't need to catch specific exceptions.

  45. How to integrate Spring and Hibernate Frameworks? (How to integrate Spring and Hibernate Frameworks?)

    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 provides support for using Spring declarative transaction management, so you should utilize that rather than going for Hibernate boiler-plate code for transaction management.

    For better understanding you should go through following tutorials:

    • Spring Hibernate Integration Example
    • Spring MVC Hibernate Integration Example

    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 provides support for using Spring declarative transaction management, so you should utilize that rather than going for Hibernate boiler-plate code for transaction management.

    For better understanding you should go through following tutorials:

    • Spring Hibernate Integration Example
    • Spring MVC Hibernate Integration Example
  46. What is Spring Security? (What is Spring Security?)

    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.

    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 the following posts to learn how to use the Spring Security framework.

    • Spring Security in Servlet Web Application
    • Spring MVC and Spring Security Integration Example

    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.

    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 the following posts to learn how to use the Spring Security framework.

    • Spring Security in Servlet Web Application
    • Spring MVC and Spring Security Integration Example
  47. How to inject a java.util.Properties into a Spring Bean? (How to inject a java.util.Properties into a Spring Bean?)

    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;

    <bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"><property name="location" value="/WEB-INF/application.properties" />
    </bean> <bean class="com.journaldev.spring.EmployeeDaoImpl"><property name="maxReadResults" value="${results.read.max}"/>
    </bean>

    If you are using annotation to configure the spring bean, then you can inject property like below.

    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. 例如;

    <bean id="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer"><property name="location" value="/WEB-INF/application.properties" />
    </bean> <bean class="com.journaldev.spring.EmployeeDaoImpl"><property name="maxReadResults" value="${results.read.max}"/>
    </bean>

    If you are using annotation to configure the spring bean, then you can inject property like below.

  48. Name some of the design patterns used in Spring Framework? (Name some of the design patterns used in Spring Framework?)

    Spring Framework is using a lot of design patterns, some of the common ones are:

    1. Singleton Pattern: Creating beans with default scope.
    2. Factory Pattern: Bean Factory classes
    3. Prototype Pattern: Bean scopes
    4. Adapter Pattern: Spring Web and Spring MVC
    5. Proxy Pattern: Spring Aspect Oriented Programming support
    6. Template Method Pattern: JdbcTemplate, HibernateTemplate etc
    7. Front Controller: Spring MVC DispatcherServlet
    8. Data Access Object: Spring DAO support
    9. Dependency Injection and Aspect Oriented Programming

    Spring Framework is using a lot of design patterns, some of the common ones are:

    1. Singleton Pattern: Creating beans with default scope.
    2. Factory Pattern : Bean Factory classes
    3. Prototype Pattern : Bean scopes
    4. Adapter Pattern : Spring Web and Spring MVC
    5. Proxy Pattern : Spring Aspect Oriented Programming support
    6. Template Method Pattern : JdbcTemplate, HibernateTemplate etc
    7. Front Controller: Spring MVC DispatcherServlet
    8. Data Access Object: Spring DAO support
    9. Dependency Injection and Aspect Oriented Programming
  49. What are some of the best practices for Spring Framework? (What are some of the best practices for Spring Framework?)

    Some of the best practices for Spring Framework are:

    1. Avoid version numbers in schema reference, to make sure we have the latest configs.
    2. Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
    3. For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
    4. Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
    5. For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
    6. 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.
    7. Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
    8. Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
    9. 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.
    10. Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don’t use it because it’s harder to maintain.

    Some of the best practices for Spring Framework are:

    1. Avoid version numbers in schema reference, to make sure we have the latest configs.
    2. Divide spring bean configurations based on their concerns such as spring-jdbc.xml, spring-security.xml.
    3. For spring beans that are used in multiple contexts in Spring MVC, create them in the root context and initialize with listener.
    4. Configure bean dependencies as much as possible, try to avoid autowiring as much as possible.
    5. For application-level properties, the best approach is to create a property file and read it in the spring bean configuration file.
    6. 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.
    7. Use correct annotations for components for understanding the purpose easily. For services use @Service and for DAO beans use @Repository.
    8. Spring framework has a lot of modules, use what you need. Remove all the extra dependencies that get usually added when you create projects through Spring Tool Suite templates.
    9. 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.
    10. Use dependency injection when there is an actual benefit, just for the sake of loose-coupling don't use it because it's harder to maintain.

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.

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.

翻译自: https://www.journaldev.com/2696/spring-interview-questions-and-answers

Spring面试问答相关推荐

  1. 25个经典的Spring面试问答

    为什么80%的码农都做不了架构师?>>>    本人收集了一些在大家在面试时被经常问及的关于Spring的主要问题,这些问题有可能在你下次面试时就会被问到.对于本文中未提及的Spri ...

  2. 100份Spring面试问答-最终名单(PDF下载)

    上次更新时间:2019年2月11日 这是有关Spring框架的一些最重要问题的摘要,在面试或面试测试过程中可能会要求您回答这些问题! 您无需担心下一次面试的机会,因为Java Code Geeks在这 ...

  3. Spring学习总结(8)——25个经典的Spring面试问答

    1.什么是Spring框架?Spring框架有哪些主要模块? Spring框架是一个为Java应用程序的开发提供了综合.广泛的基础性支持的Java平台.Spring帮助开发者解决了开发中基础性的问题, ...

  4. 关于Spring的69个面试问答和Top25个问答--终极列表,以及Spring相关知识

    Spring 框架越来越流行,很多大型系统用到,了解Spring的面试题有助简要短时间于了解对应的知识, 关于Spring的69个面试问答--终极列表 http://www.importnew.com ...

  5. web前端面试问答_Web服务面试问答

    web前端面试问答 在这篇文章中,我们涵盖了您需要熟悉的Web服务概念的几乎所有部分,以回答任何层级问题. 您还将在分类中找到最佳的Web服务面试问题和答案,因此只有在必要时才可以使用特定条款. 今天 ...

  6. Spring面试问题

    还可以查看我们最新的文章69Spring面试问答-最终名单 . 1)什么是春天? 回答: Spring是控件和面向方面的容器框架的轻量级转换. 2)解释春天? 回答: 轻巧:在尺寸和透明度方面, Sp ...

  7. jsf面试题_JSF面试问答

    jsf面试题 I have written a lot on JSF framework recently, so it's high time I write one on JSF intervie ...

  8. hibernate面试问题_Hibernate面试问答

    hibernate面试问题 Hibernate is one of the most widely used ORM tool for Java applications. It's used a l ...

  9. 程序员面试:电话面试问答Top 50

    今年是2015年,在过去几年中,电面(电话面试)是筛选程序员职位候选人的最流行的方式.它让雇佣双方很容易互相了解对方,候选人不需要去未来雇主的所在地,面试官也不用做额外的安排.这是我介绍程序员面试问题 ...

最新文章

  1. mysql ltree_mysq基础知识总结l
  2. 在深度神经网络中你有多吸引人?
  3. 正则表达式 php 模板,PHP中正则表达式回顾(4)--编写一个非常简单而且山寨的smarty模板引擎...
  4. 编程珠玑 15.3生成文本
  5. Qt学习笔记之QTranslator
  6. 【C#】获取网页内容及HTML解析器HtmlAgilityPack的使用
  7. 解决IllegalStateException: Can not perform this action after onSaveInstanceState
  8. python中beautifulsoup是什么库_BeautifulSoup库详解(个人整理)
  9. python methodtype_Python的实例定属性和方法或类绑定方法
  10. android novate乱码,Novate 一款Android RxStyle的网络框架
  11. DOM中Property与Attribute的区别
  12. macbook配置java环境变量_如何安装Java和配置环境变量
  13. qml 时间控件_Qt编写自定义控件54-时钟仪表盘
  14. AcWing 2019. 拖拉机(双端BFS)
  15. oracle otl,使用OTL操作Oracle数据库
  16. linux SFTP用户创建 不允许用户登录,并且连接只允许在制定的目录下进行操作
  17. QQ空间批量删除说说
  18. java wsdl 参数必填设置
  19. 这4款风格各异的电脑软件,免费又实用,后悔没早点知道
  20. k神讲故事-金融的结局

热门文章

  1. Windwows7 下安装mysql5
  2. [转载] Python 字典删除元素clear、pop、popitem
  3. [转载] pandas dataframe 提取行和列
  4. [转载] 50个数据可视化最有价值的图表(附完整Python代码,建议收藏)
  5. list排序成员函数对string对象与char*对象排序的差别
  6. __new__()方法的使用和实例化
  7. C语言中数组变量和指针变量
  8. 基本运算符中Swift和Java的比较
  9. Quartz.NET 入门
  10. 关于 java jdk 环境变量的配置