spring a few interview questions

Spring is a lightweight development framework aimed at improving development efficiency and maintainability of the system developers. Spring's official website: https: //spring.io/.

We generally say that the Spring Framework are references to the Spring Framework, which is a collection of many modules, the use of these modules can be easily help us develop. These modules are: core container, data access / integration ,, Web, AOP (Aspect Oriented Programming), tools, modules and test message. For example: Core Container Core component is the core of all components Spring, Beans, and component is the base component Context IOC and dependency injection, AOP component is used to implement Oriented Programming.

Spring Spring's six features listed in the official website:

  • The core technology  : Dependency Injection (DI), AOP, events (events), resources, i18n, validation, data binding, type conversion, SpEL.

  • Test  : mock objects, TestContext framework, Spring MVC test, WebTestClient.

  • Data Access  : Transaction, DAO support, JDBC, ORM, marshalling XML.

  • Web support  : Spring MVC and Spring WebFlux Web framework.

  • Integration  : Remoting, JMS, JCA, JMX, e-mail, tasks, scheduling, caching.

  • Language  : Kotlin, Groovy, a dynamic language.

List some important Spring module?

FIG Spring4.x is the corresponding version. Currently Portlet components in the latest version 5.x Web module has been discarded, while increasing the WebFlux components for asynchronous responsive process. Spring main module

  • Spring Core:  base, it can be said Spring All other features are dependent on the needs of the library. The main function of providing IOC dependency injection.

  • Aspects the Spring   : The module is integrated with the support of AspectJ.

  • AOP the Spring  : provides aspect-oriented programming.

  • JDBC the Spring  : the Java Database Connectivity.

  • JMS the Spring  : the Java Message Service.

  • ORM the Spring  : support for Hibernate and other ORM tools.

  • Web the Spring  : provide support for creating Web applications.

  • The Test the Spring  : provides support for JUnit and TestNG tests.

Talk about their understanding of the Spring IoC and AOP

IoC

IoC (Inverse of Control: Inversion of Control) is a design idea is  to create objects originally in the program manual control, handed over to the Spring framework to manage.  IoC in other languages also has applications not Spirng unique. Spring IoC container is used to achieve IoC vectors, is actually a IoC container Map (key, value), Map is stored in various objects.

The interdependence between the IOC container objects to be managed by the IOC container objects to complete injection. This can greatly simplify application development, application freed from the complex dependencies. IOC container are like a factory, when we need to create an object, you can just configure the configuration file / annotation can be, no need to consider how objects are created out of.  In a real project a Service class may have hundreds or even thousands of class as its underlying, if we need to instantiate the Service, you may want to find out every time the constructor of this Service all the underlying class, which could the people crazy. If the use of the IOC, you only need to configure, and where necessary quoted on the line, which greatly increases the maintainability of the project and reduce the development effort.

Spring era we generally configured through XML file Bean, who later developed XML files to configure feel very good, so SpringBoot configuration notes slowly began to pop up.

Recommended reading: https: //www.zhihu.com/question/23277575/answer/169698662

Spring IOC initialization process: 

 

Spring IOC initialization process

 

IOC source Read

  • https://javadoop.com/post/spring-ioc

AOP

AOP (Aspect-Oriented Programming: Oriented Programming) can be those regardless of the service, but a logical or liabilities (such as transaction processing, log management, access control, etc.) service module jointly called encapsulated , to facilitate code duplication reduction system , to reduce the coupling between modules , and is conducive to the future scalability and maintainability .

Spring AOP is the dynamic agent-based , if you want to proxy object implements an interface, then Spring AOP will use JDK Proxy , to create a proxy object, but the object does not implement an interface, you can not use the JDK Proxy to proxy the this time Spring AOP uses Cglib  , this time Spring AOP uses  Cglib  generating a subclass of the object as a proxy agent, as shown below:

SpringAOPProcess

Of course, you can also use AspectJ, Spring AOP has been integrated with AspectJ, AspectJ should be counted on the Java ecosystem is the most complete of the AOP framework.

After using AOP we can put some common functions abstracted, use can be used directly where it is needed, which greatly simplifies the code amount. It is also convenient when we need to add new features, which would also increase the scalability of the system. Logging, transaction management, and so on scene have used the AOP.

Spring AOP and AspectJ AOP What is the difference?

Enhanced belonging run Spring AOP, and AspectJ is an enhanced compilation.  Spring AOP based agent (Proxying), based on the AspectJ bytecode manipulation (Bytecode Manipulation).

Spring AOP has been integrated with AspectJ, AspectJ should be counted on the Java ecosystem is the most complete of the AOP framework. Spring AOP AspectJ compared to the more powerful, but Spring AOP relatively more simple,

If we cut surface is relatively small, so little performance difference between the two. However, when cut too much, the best choice for AspectJ, it is much faster than Spring AOP.

Spring bean in the scope of what?

  • singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。

  • prototype : 每次请求都会创建一个新的 bean 实例。

  • request : 每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTP request内有效。

  • session : 每一次HTTP请求都会产生一个新的 bean,该bean仅在当前 HTTP session 内有效。

  • global-session:全局session作用域,仅仅在基于portlet的web应用中才有意义,Spring5已经没有了。Portlet是能够生成语义代码(例如:HTML)片段的小型Java Web插件。它们基于portlet容器,可以像servlet一样处理HTTP请求。但是,与 servlet 不同,每个 portlet 都有不同的会话

Spring 中的单例 bean 的线程安全问题了解吗?

大部分时候我们并没有在系统中使用多线程,所以很少有人会关注这个问题。单例 bean 存在线程问题,主要是因为当多个线程操作同一个对象的时候,对这个对象的非静态成员变量的写操作会存在线程安全问题。

常见的有两种解决办法:

  1. 在Bean对象中尽量避免定义可变的成员变量(不太现实)。

  2. 在类中定义一个ThreadLocal成员变量,将需要的可变成员变量保存在 ThreadLocal 中(推荐的一种方式)。

Spring 中的 bean 生命周期?

这部分网上有很多文章都讲到了,下面的内容整理自:https://yemengying.com/2016/07/14/spring-bean-life-cycle/ ,除了这篇文章,再推荐一篇很不错的文章 :https://www.cnblogs.com/zrtqsk/p/3735273.html 。

  • Bean 容器找到配置文件中 Spring Bean 的定义。

  • Bean 容器利用 Java Reflection API 创建一个Bean的实例。

  • 如果涉及到一些属性值 利用 set()方法设置一些属性值。

  • 如果 Bean 实现了 BeanNameAware 接口,调用 setBeanName()方法,传入Bean的名字。

  • 如果 Bean 实现了 BeanClassLoaderAware 接口,调用 setBeanClassLoader()方法,传入 ClassLoader对象的实例。

  • 如果Bean实现了 BeanFactoryAware 接口,调用 setBeanClassLoader()方法,传入 ClassLoade r对象的实例。

  • 与上面的类似,如果实现了其他 *.Aware接口,就调用相应的方法。

  • 如果有和加载这个 Bean 的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessBeforeInitialization() 方法

  • 如果Bean实现了InitializingBean接口,执行afterPropertiesSet()方法。

  • 如果 Bean 在配置文件中的定义包含 init-method 属性,执行指定的方法。

  • 如果有和加载这个 Bean的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessAfterInitialization() 方法

  • 当要销毁 Bean 的时候,如果 Bean 实现了 DisposableBean 接口,执行 destroy() 方法。

  • 当要销毁 Bean 的时候,如果 Bean 在配置文件中的定义包含 destroy-method 属性,执行指定的方法。

图示:

 

Spring Bean 生命周期

 

与之比较类似的中文版本:

 

Spring Bean 生命周期

 

说说自己对于 Spring MVC 了解?

谈到这个问题,我们不得不提提之前 Model1 和 Model2 这两个没有 Spring MVC 的时代。

  • Model1 时代 : 很多学 Java 后端比较晚的朋友可能并没有接触过 Model1 模式下的 JavaWeb 应用开发。在 Model1 模式下,整个 Web 应用几乎全部用 JSP 页面组成,只用少量的 JavaBean 来处理数据库连接、访问等操作。这个模式下 JSP 即是控制层又是表现层。显而易见,这种模式存在很多问题。比如①将控制逻辑和表现逻辑混杂在一起,导致代码重用率极低;②前端和后端相互依赖,难以进行测试并且开发效率极低;

  • Model2 时代 :学过 Servlet 并做过相关 Demo 的朋友应该了解“Java Bean(Model)+ JSP(View,)+Servlet(Controller) ”这种开发模式,这就是早期的 JavaWeb MVC 开发模式。Model:系统涉及的数据,也就是 dao 和 bean。View:展示模型中的数据,只是用来展示。Controller:处理用户请求都发送给 ,返回数据给 JSP 并展示给用户。

Model2 模式下还存在很多问题,Model2的抽象和封装程度还远远不够,使用Model2进行开发时不可避免地会重复造轮子,这就大大降低了程序的可维护性和复用性。于是很多JavaWeb开发相关的 MVC 框架营运而生比如Struts2,但是 Struts2 比较笨重。随着 Spring 轻量级开发框架的流行,Spring 生态圈出现了 Spring MVC 框架, Spring MVC 是当前最优秀的 MVC 框架。相比于 Struts2 , Spring MVC 使用更加简单和方便,开发效率更高,并且 Spring MVC 运行速度更快。

MVC 是一种设计模式,Spring MVC 是一款很优秀的 MVC 框架。Spring MVC 可以帮助我们进行更简洁的Web层的开发,并且它天生与 Spring 框架集成。Spring MVC 下我们一般把后端项目分为 Service层(处理业务)、Dao层(数据库操作)、Entity层(实体类)、Controller层(控制层,返回数据给前台页面)。

Spring MVC 的简单原理图如下:

 

 

SpringMVC 工作原理了解吗?

原理如下图所示:

 

SpringMVC运行原理

 

上图的一个笔误的小问题:Spring MVC 的入口函数也就是前端控制器 DispatcherServlet 的作用是接收请求,响应结果。

流程说明(重要):

  1. 客户端(浏览器)发送请求,直接请求到 DispatcherServlet

  2. DispatcherServlet 根据请求信息调用 HandlerMapping,解析请求对应的 Handler

  3. 解析到对应的 Handler(也就是我们平常说的 Controller 控制器)后,开始由 HandlerAdapter 适配器处理。

  4. HandlerAdapter 会根据 Handler来调用真正的处理器开处理请求,并处理相应的业务逻辑。

  5. 处理器处理完业务后,会返回一个 ModelAndView 对象,Model 是返回的数据对象,View 是个逻辑上的 View

  6. ViewResolver 会根据逻辑 View 查找实际的 View

  7. DispaterServlet 把返回的 Model 传给 View(视图渲染)。

  8. 把 View 返回给请求者(浏览器)

Spring 框架中用到了哪些设计模式?

关于下面一些设计模式的详细介绍,可以看笔主前段时间的原创文章《面试官:“谈谈Spring中都用到了那些设计模式?”。》 。

  • 工厂设计模式 : Spring使用工厂模式通过 BeanFactoryApplicationContext 创建 bean 对象。

  • 代理设计模式 : Spring AOP 功能的实现。

  • 单例设计模式 : Spring 中的 Bean 默认都是单例的。

  • 模板方法模式 : Spring 中 jdbcTemplatehibernateTemplate 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。

  • 包装器设计模式 : 我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库。这种模式让我们可以根据客户的需求能够动态切换不同的数据源。

  • 观察者模式: Spring 事件驱动模型就是观察者模式很经典的一个应用。

  • 适配器模式 :Spring AOP 的增强或通知(Advice)使用到了适配器模式、spring MVC 中也是用到了适配器模式适配Controller

  • ……

@Component 和 @Bean 的区别是什么?

  1. 作用对象不同: @Component 注解作用于类,而@Bean注解作用于方法。

  2. @Component通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中(我们可以使用 @ComponentScan 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。@Bean 注解通常是我们在标有该注解的方法中定义产生这个 bean,@Bean告诉了Spring这是某个类的示例,当我需要用它的时候还给我。

  3. @Bean 注解比 Component 注解的自定义性更强,而且很多地方我们只能通过 @Bean 注解来注册bean。比如当我们引用第三方库中的类需要装配到 Spring容器时,则只能通过 @Bean来实现。

@Bean注解使用示例:

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }

}

上面的代码相当于下面的 xml 配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

下面这个例子是通过 @Component 无法实现的。

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return new serviceImpl3();
    }
}

将一个类声明为Spring的 bean 的注解有哪些?

我们一般使用 @Autowired 注解自动装配 bean,要想把类标识成可用于 @Autowired注解自动装配的 bean 的类,采用以下注解可实现:

  • @Component :通用的注解,可标注任意类为 Spring 组件。如果一个Bean不知道属于拿个层,可以使用@Component 注解标注。

  • @Repository : 对应持久层即 Dao 层,主要用于数据库相关操作。

  • @Service : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao层。

  • @Controller : 对应 Spring MVC 控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。

Spring 管理事务的方式有几种?

  1. 编程式事务,在代码中硬编码。(不推荐使用)

  2. 声明式事务,在配置文件中配置(推荐使用)

声明式事务又分为两种:

  1. 基于XML的声明式事务

  2. 基于注解的声明式事务

Spring 事务中的隔离级别有哪几种?

TransactionDefinition 接口中定义了五个表示隔离级别的常量:

  • TransactionDefinition.ISOLATION_DEFAULT: 使用后端数据库默认的隔离级别,Mysql 默认采用的 REPEATABLE_READ隔离级别 Oracle 默认采用的 READ_COMMITTED隔离级别.

  • TransactionDefinition.ISOLATION_READ_UNCOMMITTED: 最低的隔离级别,允许读取尚未提交的数据变更,可能会导致脏读、幻读或不可重复读

  • TransactionDefinition.ISOLATION_READ_COMMITTED: 允许读取并发事务已经提交的数据,可以阻止脏读,但是幻读或不可重复读仍有可能发生

  • TransactionDefinition.ISOLATION_REPEATABLE_READ: 对同一字段的多次读取结果都是一致的,除非数据是被本身事务自己所修改,可以阻止脏读和不可重复读,但幻读仍有可能发生。

  • TransactionDefinition.ISOLATION_SERIALIZABLE: 最高的隔离级别,完全服从ACID的隔离级别。所有的事务依次逐个执行,这样事务之间就完全不可能产生干扰,也就是说,该级别可以防止脏读、不可重复读以及幻读。但是这将严重影响程序的性能。通常情况下也不会用到该级别。

Spring 事务中哪几种事务传播行为?

支持当前事务的情况:

  • TransactionDefinition.PROPAGATION_REQUIRED: 如果当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。

  • TransactionDefinition.PROPAGATION_SUPPORTS:  If the current transaction exists, it is added to the transaction; if no transaction, non-transactional way places continue to run.

  • TransactionDefinition.PROPAGATION_MANDATORY:  If the current transaction exists, it is added to the transaction; if no transaction, an exception is thrown. (Mandatory: Mandatory)

It does not support the current transaction situation:

  • TransactionDefinition.PROPAGATION_REQUIRES_NEW:  create a new transaction, if the current transaction exists, put the current transaction pending.

  • TransactionDefinition.PROPAGATION_NOT_SUPPORTED:  non-transaction run, if the current transaction exists, put the current transaction pending.

  • TransactionDefinition.PROPAGATION_NEVER:  non-transaction run, if the current transaction exists, an exception is thrown.

Other cases:

  • TransactionDefinition.PROPAGATION_NESTED:  If the current transaction exists, create a transaction to run as the current nested transaction transaction; if no transaction, the value is equivalent to TransactionDefinition.PROPAGATION_REQUIRED.

Guess you like

Origin www.cnblogs.com/HHR-SUN/p/11566449.html