Spring face questions Highlights (selection)

The following were collected from the network, can not find the original source. The main collection for the interview, I want to help ~ ~ ~ ~

Spring face questions Highlights (selection)

1. What is Spring?

Spring is an open source Java EE development framework. The core functions of Spring Framework can be applied in any Java application, but there are better scalability of Web applications on the Java EE platform. Spring Framework's goal is to make the development of Java EE applications more simple, by using the POJO-based programming model to promote good programming style.

2.Spring What are the advantages?

  • Lightweight: Spring in terms of absolute size and transparency belong lightweight, basic version of the Spring framework only about 2MB.
  • Inversion of Control (IOC): Spring using inversion of control technology to achieve loose coupling. Dependence is injected into an object, instead of creating or looking for dependent objects.
  • Aspect Oriented Programming (AOP): Spring aspect-oriented programming support, while the business logic of applications and system services separate.
  • Container: Spring contain and manage the application object configuration and life cycle.
  • MVC framework: Spring web framework is a well-designed web MVC framework, to replace some of the good web framework.
  • Transaction management: Spring next to a local business to a global business (JAT) provides a unified transaction management interface.
  • Exception Handling: Spring provides a convenient API abnormality particular technique (thrown by JDBC, Hibernate, or JDO) into uniform, Unchecked exception.

3. Spring affairs to achieve what way?

  • Programmatic transaction management: This means that you can bring a great deal of flexibility programmatically manage affairs in this way, but it is difficult to maintain.
  • Declarative transaction management: This approach means that you can separate transaction management and business code. You only need annotations or XML configuration management affairs.

Transaction management framework 4.Spring What are the advantages?

  • It provides a unified programming model across different transaction API (such as JTA, JDBC, Hibernate, JPA, and JDO).
  • It provides a simple API rather than a series of complex transactions API (eg JTA). It supports declarative transaction management for the programmatic transaction management.
  • It can be well integrated and Spring's various data access technologies.

5.spring transaction definition of propagation rules

  • PROPAGATION_REQUIRED: support for the current transaction, if no transaction, we create a new business. This is the most common choice.
  • PROPAGATION_SUPPORTS: support for the current transaction, if no transaction is executed in a non-transactional way.
  • PROPAGATION_MANDATORY: support for the current transaction, if no transaction, throw an exception.
  • PROPAGATION_REQUIRES_NEW: New Transaction, if the current transaction exists, the current transaction pending.
  • PROPAGATION_NOT_SUPPORTED: performing an operation to a non-transactional way, if the current transaction exists, put the current transaction pending.
  • PROPAGATION_NEVER: to perform non-transactional way, if the current transaction exists, an exception is thrown.
  • PROPAGATION_NESTED: If the current transaction exists, it is executed within nested transactions. If no transaction is carried out with PROPAGATION_REQUIRED similar operations.

6.Spring underlying principle Affairs

  • Division processing unit --IoC

Since the spring is a problem for single database transaction processing locally, the specific implementation first transaction processing unit is divided in the spring IoC. Various configurations of the transaction and will put ioc container (provided the transaction manager, the transaction set and the propagation characteristics of isolation mechanism).

  • AOP interceptors need for transaction processing class

Spring transaction module is implemented by declarative transactions AOP function, specific operations (such as the configuration and implementation of read transaction, the transaction object abstract), with the use of AOP TransactionProxyFactoryBean interface function to generate the proxy proxy object, complete TransactionInterceptor interception proxy approach, weaving function of the transaction to the method of interception. Ioc container configuration read transaction attributes, data structures, internal conversion (The TransactionAttributeSourceAdvisor used) is required for the transaction spring, TransactionAttribute conversion data object representation.

  • To implement transaction processing (generation, commit, rollback, suspend)

spring entrusted to the specific transaction processor. Implement an abstract and adaptation. Specific transaction processor adapted: DataSource Data source supports, hibernate transaction support source data, JDO transaction support source data, JPA, JTA transaction support source data. These are supported by design PlatformTransactionManager, support AbstractPlatforTransaction a series of transactions. TransactionManager offers a range of commonly used data source support.

  • Combine

PlatformTransactionManager realized TransactionInterception interface let combined with TransactionProxyFactoryBean, form a system design Spring declarative transaction.

7. Spring singleton implementation principle

The Spring Framework is supported by way of a single example of a single embodiment registry were implemented, the registry is cached HashMap object, if the configuration information in the configuration file does not require the use of a single embodiment, will use the new Spring return way of example object instance.

8. What are the different types of IOC (dependency injection)?

  • Constructor dependency injection: constructor dependency injection is completed when the container trigger constructor, this configuration has a number of parameters, each representing an object injection.
  • Setter injection method relies on: a first container triggers no argument constructor or no-argument static factory method to instantiate an object, then calling setter methods bean container is completed Setter method relies injection.

  • Annotations injection: @Autowired based automatic assembly, the default is the type of injection, it can be used for constructors, fields, methods injection.

9. dependency injection you recommend what? Constructor dependency injection method or Setter Dependency Injection?

You can use the two methods simultaneously dependency injection, the best option is implemented using constructor dependency injection force using setter methods implemented optional dependencies.

10. briefly Spring Framework?

concept

  • Spring is committed to Java EE application solutions, it is a lightweight framework that simplifies the development of enterprise-class Java provides a powerful, stable function.
  • Spring has two main objectives: first, to make it easier to use the prior art, the second is the promotion of good programming practice (or called best practices)

advantage

  • Lightweight: Spring in terms of absolute size and transparency belong lightweight, basic version of the Spring framework only about 2MB
  • Inversion of Control (IOC): Spring using inversion of control technology to achieve loose coupling. Dependence is injected into an object, instead of creating or looking for dependent objects.
  • Convenient decoupling, simplify development: Spring is a large factory, you can create and maintain dependence of all objects, to manage Spring
  • AOP programming support: Spring provides aspect-oriented programming, you can easily implement a program permission to intercept, monitoring and other functions run
  • Support for declarative transactions: only through configuration management to complete the transaction without the need for manual programming
  • Easy integration of a variety of excellent framework: Spring does not exclude a variety of excellent open source framework, which provides a variety of excellent internal framework: direct support (such as Struts2, Hibernate, MyBatis, Quartz, etc.)

  • JavaEE API to reduce the use of difficulty: Spring for some API JavaEE development is very difficult to use (JDBC, JavaMail, remote calls, etc.), provides packaging that greatly reduces the difficulty of these API application

11. Spring brief seven modules?

  • Spring Core: Core capsule is the most fundamental part of the framework, to provide IOC and dependency injection characteristics. The basic concept here is the BeanFactory, which provides for the Classical Factory pattern to eliminate the need for programmatic singletons and allows you really separated dependencies and program logic from the configuration.

  • Spring Context: Context built capsule encapsulation packet based on the Core, object access method provides a framework-style, somewhat like a JNDI-registry. Context encapsulated packet characteristics derived from Beans encapsulated packet, and adds support for internationalization (I18N) of (for example resource bundles), event propagation, transparent way to create a resource loading and Context, for example by Servlet container.

  • Spring DAO: DAO (Data Access Object) provides a JDBC-abstraction layer, it can eliminate the error code tedious JDBC coding and parsing of database-vendor specific. And, JDBC package also provides a better package than the programming of declarative transaction management methods, not only to achieve a particular interface, but for all of POJOs (plain old Java objects) are applicable.

  • Spring ORM: ORM package provides a common "object / relational" mapping the integration layer APIs. Including JPA, JDO, Hibernate and iBatis. Using the ORM package, can be mixed with all the characteristics provided by the Spring "O / R" mapping, simple declarative transaction management feature mentioned previously.

  • Spring AOP: Spring AOP package provides the programming oriented AOP Alliance-compliant implementation allows you to define, for example, a method interceptor (method-interceptors) and the tangential point (pointcuts), logically, thus weakening the code coupling features, they are clearly separated. Moreover, the use of source-level metadata functionality, you can also merge a variety of behavioral information into your code.

  • Spring Web: Spring's Web package provides basic Web development-oriented integration features, such as multi-file uploads, the use of Servlet listeners were ApplicationContext IOC container initialization and for the Web. When used in conjunction with the Spring WebWork or Struts, this is the package may be combined with other Spring frame.

  • Spring Web MVC: Spring in MVC package provides a Web application Model-View-Controller (MVC) implementation. Spring MVC framework provides not only a conventional implementation that provides a clear separation model, in the areas between the model code and Web Form. And, also by means of other features of the Spring Framework.

12. Spring Design Patterns

spring commonly used design patterns to achieve nine, at our example:

The first: simple factory

Also known as static factory method (StaticFactory Method) mode, but does not belong to one of 23 kinds of GOF design patterns. The essence of simple factory pattern is a class factory according to the parameters passed, the dynamic should decide which class to create a product. spring in the BeanFactory is the embodiment of simple factory pattern to obtain a bean object from the passed unique identifier, whether but after passing parameters to create or passed to create this situation should be based on specific parameters before.

The second: factory method (Factory Method)

Typically used by new applications to directly create new objects, in order to create and use objects of phase separation, the use of the factory model, that application will create and initialize the object's responsibilities to the factory object. Under normal circumstances, the application has its own factory object to create the bean. If the application is subject to the Spring own factory management, the management of Spring is not common bean, but the factory Bean.

Third: singleton pattern (the Singleton)

To ensure that a class has only one instance and provide a global access point to access it.
After a single spring embodiment mode, a half of the sentence is completed, i.e., provides global access point BeanFactory. But no single embodiment to control the level of the builder, since spring management is arbitrary java object.

Fourth: Adapter (Adapter)

Aop in the Spring, the Advice used (notification) to enhance the functionality of the proxy class. Spring AOP to achieve this principle on the use of proxy functionality mode (1, JDK dynamic proxy .2, CGLib byte code generation techniques agent.) Based on the method of reinforcing section level, i.e., the proxy class is generated proxy class, and before the proxy class method is provided interceptor, the agent enhances the functionality of the method by performing block content high regard, aspect-oriented programming implementation.

Fifth: wrapper (Decorator)

Encountered such a problem in our project: Our project need to connect multiple databases, and different customers will each visit to access different databases as needed. In the past, we always spring and hibernate framework to configure a data source, thus sessionFactory the dataSource property always point to the data source and constant, all DAO when using sessionFactory is through this data source to access the database. But now, due to the need of the project, we have to constantly switch DAO when accessing sessionFactory in multiple data sources, the question arises: how to make sessionFactory performing data persistence time, according to customer demand can dynamically switch different data sources? We can not be resolved within the framework of the spring by minor modifications? Are there any design patterns can make use of it? First, think of all dataSource configured in the spring of applicationContext in. These dataSource may be of different types, such as different databases: Oracle, SQL Server, MySQL, etc., may also be different data sources: for example org.apache.commons.dbcp.BasicDataSource apache offer, spring offer org. springframework.jndi.JndiObjectFactoryBean and so on. The sessionFactory then each request by a client, the dataSource attribute set to different data sources, in order to achieve the purpose of switching the data source.
spring used in the packaging mode in two forms in the class name: one is the class name contained Wrapper, another is the class name contained Decorator. Basically to an object dynamically add some additional responsibilities.

Sixth: proxy (Proxy)

Providing a proxy to control access to the object to other objects. Structurally Decorator pattern and the like, but is controlled Proxy, more like a restriction on the function, and increase duty Decorator.
The spring has reflected in the Proxy mode aop, such JdkDynamicAopProxy and Cglib2AopProxy.

Seventh: observer (Observer)

Definition of the dependencies between the subject an-many, when a state of the object changes, all objects that depend on it have been notified and updated automatically.
spring in Observer mode is commonly used in place of the realization of listener. As ApplicationListener.

Eighth: Strategy (Strategy)

Define a series of algorithms, encapsulate them one by one, and makes them interchangeable. This mode makes the algorithm can be varied independently of the clients that use it.

Ninth: Method template (Template Method)

The algorithm defines a skeleton of the operation, some steps to subclasses delay. Template MethodSubclasses that may not change the structure of certain steps of an algorithm of the algorithm to redefine.
Template MethodInheritance pattern is generally required. Here we want to explore another kind of Template Methodunderstanding. spring in JdbcTemplate, does not want to inherit when using this class of this class, because too many methods of this class, but we still want to have a stable used JdbcTemplate, public database connection, so how do we do? We can change things out of ways to JdbcTemplate passed as a parameter. But things are changing a code, and the code will be used in JdbcTemplate variables. How to do? Then we use the callback object bar. Define a method JdbcTemplate manipulated variable in this callback object, we have to implement this method, put the change of focus to something here. Then we pass this callback object to JdbcTemplate, thus completing the call. This may be Template Method does not need to inherit another way to achieve it.

13.ApplicationContext difference with the BeanFactory

Both are loaded through the bean xml configuration file, ApplicationContextand BeanFacotrycompared to provide additional extension, but the main difference is that the latter is delayed loading, if not a single property Bean injection, BeanFacotryafter loading, until the first use call getBean method will throw an exception; while the ApplicationContext in the initialization test itself, which will help to check whether the dependency property injection; so usually we choose to use ApplicationContext.

BeanFactroyUses a form of lazy loading to inject Bean, that is only in use to a Beantime (call getBean ()), only to load the Bean is instantiated, so that we can not find some of the existing Springconfiguration problems. And ApplicationContexton the contrary, it is when the container starts, all created at once Bean. Thus, when the container starts, we can find Springa configuration error exists.

BeanFactoryAnd ApplicationContextsupport BeanPostProcessor, BeanFactoryPostProcessorthe use, but the difference between the two is: BeanFactorythe need to manually register, and ApplicationContextit is automatically registered

14. How to understand IoC and DI?

IOC:
IOC is Inversion of Control, popular to say that we do not create an instance of the object itself, these are handed over to the Spring bean factory to help us to create management. This is the core idea of Spring, by way of interface-oriented programming to achieve dynamic dependence on the business component. This means that the IOC is the Spring coupling for settlement procedures exist. In practice, Spring specified by the configuration file (xml or properties) needs to instantiate java class (the class name of the full string), comprising a set of initial values of these java classes, reading the configuration file by loading provided by Spring the method (getBean ()) you can get to an instance of an object is initialized according to the specified configuration we want.

  • Advantages: IOC dependency injection or reduces the amount of code of the application. It makes the application of the test is very simple because it requires a single embodiment or JNDI lookup mechanism is no longer in the cell test. Simple implementation and less interference mechanism such that loose coupling is achieved. IOC container support ground singletons and delay loading service.

** DI: DI-Dependency ** Injection, namely "dependency injection": dependencies between components at runtime is determined by the vessel, said the image that will be injected by the container dynamic dependencies into a component. Dependency injection is not intended to bring more functionality to software systems, but to enhance component reuse frequencies, and for the system to build a flexible, scalable platform. Via dependency injection mechanism, we need only a simple configuration, without any code can specify the target resources needed to complete their business logic without having to be concerned about the specific resources come from, who to achieve.

15. introduce AOP related terms?

  • Section (Aspect): the extracted common module, may cross multiple objects. In Spring AOP, aspects are implemented using class (style based mode) or @AspectJ annotation to be implemented in the general category.

  • Connection point (Join point): refers to a method, in Spring AOP, a connection point always represents a method execution.

  • Notification (Advice): action performed on a particular section of the connection point (Join point). Different types of advice, including "around", "before" and "after" and the like notified. Many AOP frameworks, including Spring, are based on advice as an interceptor model, and maintain a connection with the center point of the interceptor chain.

  • Entry point (Pointcut): refers to the starting point we have to define which intercept Join point right. By pointcut expression specified intercept method, such as specifying intercept the Add , Search .

  • Introduction (Introduction) :( also called internal type declaration (inter-type declaration)). Declare additional methods or certain types of fields. Spring allows the introduction of new interfaces (and a corresponding implementation) to any object in the proxy. For example, you could use an introduction to the bean implementation IsModified interface, to simplify caching.

  • Audience (Target Object): being notified by one or more section (aspect) (advise) object. Some people call it being notified (adviced) objects. Since Spring AOP is achieved by running a proxy, this object is always to be a proxy (proxied) objects.

  • Weaving (Weaving): refers to the enhancement applied to the target object to create new proxy object of the process. Spring is done at runtime weaving.

Concept pointcut (the pointcut) and the connection point (join point) matches the AOP is the key, which makes it different from the other AOP offering only interception of the old technology. Pointcuts enable (the advice) independently of the level of OO. For example, to provide a statement transaction management around advice can be applied to a set of objects across a plurality of methods (e.g., all business service layer operations).

AOP related terms

16. How do you understand Spring AOP?

concept

Oriented Programming. AOP is a continuation of OOP is a hot software development, an important element is the Spring framework, using AOP can isolate each part of the business logic, so that the business logic to reduce the degree of coupling between the parts, to improve program reusability, while improving the efficiency of development.

The core idea
can not modify the source code under the premise of the program enhanced

The principle
agent technology underlying Spring Framework AOP techniques are employed, a so-called dynamic proxy AOP framework that is not to modify the byte code, but rather generates a temporary method AOP object in memory, the object contains the target object AOP all the way and make a specific cut-off point in the enhancement process, and the callback original object. Spring AOP dynamic proxy There are two main ways, JDKdynamic proxies and CGLIBdynamic proxies.

  • JDKDynamic agent: receiving the proxy class through reflection, and requires the proxy class must implement an interface. The core JDK dynamic proxy is InvocationHandler interface and the Proxy class.

  • CGLIB动态代理: 如果目标类没有实现接口,那么 Spring AOP 会选择使用 CGLIB 来动态代理目标类 。CGLIB ( Code Generation Library ),是一个代码生成的类库,可以在运行时动态的生成某个类的子类,注意, CGLIB 是通过继承的方式做的动态代理,因此如果某个类被标记为 final ,那么它是无法使用 CGLIB 做动态代理的。

17. Spring中有哪些增强处理,区别?

  • 前置增强:org.springframework.aop.BeforeAdvice代表前置增强,表示在目标方法整形前实施增强
  • 后置增强:org.springframework.aop.AfterReturningAdvice代表后置增强,表示在目标方法执行后实施增强
  • 环绕增强:org.springframework.aop.MethodInterceptor代表环绕增强,表示在目标方法执行前后实施增强
  • 异常抛出增强 :org.springframework.aop.ThrowsAdvice代表抛出异常增强,表示在目标方法抛出异常后实施增强
  • 引介增强:org.springframework.aop.IntroductionInterceptor代表引介增强,表示在目标类中添加一些新的方法和属性

18. Spring中支持的Bean作用域有哪些?

支持如下五种不同的作用域

  • Singleton(默认):在Spring IOC容器中仅存在一个Bean实例,Bean以单实例的方式存在。
  • Prototype:一个bean可以定义多个实例
  • Request:每次HTTP请求都会创建一个新的Bean。该作用域仅适用于WebApplicationContext环境。
  • Session:一个HTTP Session定义一个Bean。该作用域仅适用于WebApplicationContext环境.
  • GolbalSession:同一个全局HTTP Session定义一个Bean。该作用域同样仅适用于WebApplicationContext环境.

19.如何定义bean的作用域?

Spring中创建一个bean的时候,我们可以声明它的作用域。只需要在bean定义的时候通过scope属性定义即可。例如,当Spring需要产生每次一个新的bean实例时,应该声明beanscope属性为prototype。如果每次你希望Spring返回一个实例,应该声明beanscope属性为singleton

20.说一说Spring框架中的bean的生命周期?

  • Spring容器读取XML文件中bean的定义并实例化bean。
  • Spring根据bean的定义设置属性值。
  • 如果该Bean实现了BeanNameAware接口,Spring将bean的id传递给setBeanName()方法。
  • 如果该Bean实现了BeanFactoryAware接口,Spring将beanfactory传递给setBeanFactory()方法。
  • 如果任何bean BeanPostProcessors 和该bean相关,Spring调用postProcessBeforeInitialization()方法。
  • 如果该Bean实现了InitializingBean接口,调用Bean中的afterPropertiesSet方法。如果bean有初始化函数声明,调用相应的初始化方法。
  • 如果任何bean BeanPostProcessors 和该bean相关,调用postProcessAfterInitialization()方法。
  • 如果该bean实现了DisposableBean,调用destroy()方法。

21.哪些是最重要的bean生命周期方法,是否能重写它们?

有两个重要的bean生命周期方法。

  • 第一个是setup方法,该方法在容器加载bean的时候被调用。
  • 第二个是teardown方法,该方法在bean从容器中移除的时候调用。
    bean标签有两个重要的属性(init-method 和 destroy-method),你可以通过这两个属性定义自己的初始化方法和析构方法。
    Spring也有相应的注解:@PostConstruct@PreDestroy

22.有几种不同类型的自动代理?

BeanNameAutoProxyCreator
DefaultAdvisorAutoProxyCreator
Metadata autoproxying

23. 什么是Spring的内部bean?

当一个bean仅被用作另一个bean的属性时,它能被声明为一个内部bean,为了定义inner bean,在Spring 的 基于XML的 配置元数据中,可以在 或 元素内使用 元素,内部bean通常是匿名的,它们的Scope一般是prototype。

24. Spring中自动装配的方式有哪些?

  • no:不进行自动装配,手动设置Bean的依赖关系。
  • byName:根据Bean的名字进行自动装配。
  • byType:根据Bean的类型进行自动装配。
  • constructor:类似于byType,不过是应用于构造器的参数,如果正好有一个Bean与构造器的参数类型相同则可以自动装配,否则会导致错误。
  • autodetect:如果有默认的构造器,则通过constructor的方式进行自动装配,否则使用byType的方式进行自动装配。

说明:自动装配没有自定义装配方式那么精确,而且不能自动装配简单属性(基本类型、字符串等),在使用时应注意。

25.你可以在Spring中注入null或空字符串吗?

完全可以。

26. 不同版本的 Spring Framework 有哪些主要功能?

Version Feature
Spring 2.5 发布于 2007 年。这是第一个支持注解的版本。
Spring 3 发布于 2009 年。它完全利用了 Java5 中的改进,并为 JEE6 提供了支持。
Spring 4.0 发布于 2013 年。这是第一个完全支持 JAVA8 的版本。。

27.spring DAO 有什么用?

Spring DAO 使得 JDBC,Hibernate 或 JDO 这样的数据访问技术更容易以一种统一的方式工作。这使得用户容易在持久性技术之间切换。它还允许您在编写代码时,无需考虑捕获每种技术不同的异常。

28. 列举 Spring DAO 抛出的异常。

spring-data-access-exception

29. spring JDBC API 中存在哪些类?

  • JdbcTemplate
  • SimpleJdbcTemplate
  • NamedParameterJdbcTemplate
  • SimpleJdbcInsert
  • SimpleJdbcCall

30.Spring AOP and AspectJ AOP 有什么区别?

Spring AOP 基于动态代理方式实现;AspectJ 基于静态代理方式实现。
Spring AOP 仅支持方法级别的 PointCut;提供了完全的 AOP 支持,它还支持属性级别的 PointCut。

推荐

大厂笔试内容集合(内有详细解析) 持续更新中....

ProcessOn是一个在线作图工具的聚合平台~

文末

欢迎关注个人微信公众号:Coder编程
欢迎关注Coder编程公众号,主要分享数据结构与算法、Java相关知识体系、框架知识及原理、Spring全家桶、微服务项目实战、DevOps实践之路、每日一篇互联网大厂面试或笔试题以及PMP项目管理知识等。更多精彩内容正在路上~
新建了一个qq群:315211365,欢迎大家进群交流一起学习。谢谢了!也可以介绍给身边有需要的朋友。

Articles included to
Github: https://github.com/CoderMerlin/coder-programming
Gitee: https://gitee.com/573059382/coder-programming
welcome attention and star ~
Micro-channel public number

Guess you like

Origin www.cnblogs.com/coder-programming/p/12002277.html