collect! What Spring must master

coldplay.xixi
Release: 2020-09-29 18:05:12
forward
2005 people have browsed it

mysql tutorialcolumn introduces what you must master about Spring.

Hello everyone! I am an enthusiastic member of the Chaoyang people.

The Spring framework is a must-ask question during interviews. What exactly does it contain? Let's take a look. This is also a question I often ask in interviews, and it also reflects a programmer's ability to understand the framework.

Introduce the Spring framework

Spring is a lightweight framework that aims to Improve the development efficiency of developers and the maintainability of the system.

What we generally call the Spring Framework is the Spring Framework. It is a collection of many modules. Using these modules can easily assist us in development. These modules are Core Containers, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Tools, Messaging, and Testing modules. For example, the Core component in Core Container is the core of all Spring components, Beans components and Context components are the basis for implementing IOC and DI, and AOP components are used to implement aspect-oriented programming.

6 features of Spring:

  • Core technologies: Dependency Injection (DI), AOP, Events, resources, i18n, validation, data binding, type conversion, SpEL;
  • Testing: Mock objects, TestContext framework, Spring MVC testing, WebTestClient;
  • Data access: transactions, DAO support, JDBC, ORM, marshaling XML;
  • Web support: Spring MVC and Spring WebFlux web framework;
  • Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, caching;
  • Language: Kotlin, Groovy, dynamic language;

List some important Spring modules

The picture below corresponds to the Spring 4.x version. The Portlet component of the Web module in the latest 5.x version has been abandoned and added WebFlux components for asynchronous reactive processing.

  • Spring Core: Basic, it can be said that all other functions of Spring depend on this class library. Mainly provides IOC and DI functions.
  • Spring Aspects: This module provides support for integration with AspectJ.
  • Spring AOP: Provides aspect-oriented programming implementation.
  • Spring JDBC: Java database connection.
  • Spring JMS: Java Message Service.
  • Spring ORM: Used to support ORM tools such as Hibernate.
  • Spring Web: Provides support for creating web applications.
  • Spring Test: Provides support for JUnit and TestNG testing.

Talk about your understanding of Spring IOC and AOP

IOC

IOC(Inversion Of Controll, Inversion of Control) is a design idea, that is The control of manually created objects in the program is handed over to the Spring framework. IOC is also used in other languages and is not specific to Spring. The IOC container is the carrier used by Spring to implement IOC. The IOC container is actually a Map (key, value), and various objects are stored in the Map.

Leave the interdependencies between objects to be managed by the IOC container, and the IOC container completes the injection of the objects. This can greatly simplify application development and free applications from complex dependencies. The IOC container is like a factory. When we need to create an object, we only need to configure the configuration file/annotations without thinking about how the object is created. In actual projects, a Service class may have hundreds or even thousands of classes as its bottom layer. If we need to instantiate this Service, we may have to figure out the constructors of all the underlying classes of this Service every time, which may confuse people. Drive crazy. If you use IOC, you only need to configure it and reference it where needed, which greatly increases the maintainability of the project and reduces the difficulty of development.

In the Spring era, we usually configured beans through XML files. Later, developers felt that using XML files to configure beans was not good, so Spring Boot annotation configuration gradually became popular.

AOP

##AOP(Aspect-Oriented Programming, aspect-oriented programming ) can encapsulate the logic or responsibilities (such as transaction processing, log management, permission control, etc.) that have nothing to do with the business but are commonly called by the business modules, so as to reduce the duplication of code in the system, reduce the coupling between modules, and have Conducive to future scalability and maintainability.

Spring AOP is based on dynamic proxy. If the object to be proxied implements a certain interface, then Spring AOP will use JDK dynamic proxy to create the proxy object; but for objects that do not implement the interface, it cannot be used. JDK dynamic proxy instead uses CGlib dynamic proxy to generate a subclass of the proxy object as a proxy.

Of course, you can also use AspectJ. Spring AOP has integrated AspectJ. AspectJ should be regarded as the most complete AOP framework in the Java ecosystem. After using AOP, we can abstract some common functions and use them directly where they are needed, which can greatly simplify the amount of code. We need to add new functions conveniently and improve the scalability of the system. AOP is used in scenarios such as logging function, transaction management, and permission management.

The difference between Spring AOP and AspectJ AOP

Spring AOP is a runtime enhancement , and AspectJ is a compile-time enhancement. Spring AOP is based on Proxying, while AspectJ is based on Bytecode Manipulation.

Spring AOP has integrated AspectJ, which should be regarded as the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simpler.

If we have fewer aspects, there will be little performance difference between the two. However, when there are too many aspects, it is best to choose AspectJ, which is much faster than SpringAOP.

What are the scopes of beans in Spring?

  1. singleton: The only bean instance, beans in Spring are all singletons by default.
  2. prototype: A new bean instance will be created with each request.
  3. request: Each HTTP request will generate a new bean, which is only valid within the current HTTP request.
  4. session: Each HTTP request will generate a new bean, which is only valid within the current HTTP session.
  5. global-session: The global session scope is only meaningful in portlet-based web applications and is no longer available in Spring 5. Portlets are small Java web plug-ins capable of generating snippets of semantic code (such as HTML). They are based on portlet containers and can handle HTTP requests like servlets. But unlike Servlets, each Portlet has a different session.

Do you understand the thread safety issues of singleton beans in Spring?

Most of the time we do not use multi-threading in the system, so few people pay attention to this issue. Singleton beans have threading problems, mainly because when multiple threads operate the same object, writing operations to the non-static member variables of this object will cause thread safety issues.

There are two common solutions:

  1. Try to avoid defining variable member variables in the bean object (not very realistic).
  2. Define a ThreadLocal member variable in the class and save the required variable member variables in ThreadLocal (a recommended way).

Bean life cycle in Spring?

  1. The Bean container finds the definition of Spring Bean in the configuration file.
  2. The Bean container uses the Java Reflection API to create a Bean instance.
  3. If some attribute values are involved, use the set() method to set some attribute values.
  4. If the Bean implements the BeanNameAware interface, call the setBeanName() method and pass in the name of the Bean.
  5. If the Bean implements the BeanClassLoaderAware interface, call the setBeanClassLoader() method and pass in the instance of the ClassLoader object.
  6. If the Bean implements the BeanFactoryAware interface, call the setBeanClassFacotory() method and pass in the instance of the ClassLoader object.
  7. Similar to the above, if other *Aware interfaces are implemented, the corresponding methods are called.
  8. If there is a BeanPostProcessor object related to the Spring container that loads this Bean, execute the postProcessBeforeInitialization() method.
  9. If the Bean implements the InitializingBean interface, execute the afeterPropertiesSet() method.
  10. If the Bean definition in the configuration file contains the init-method attribute, execute the specified method.
  11. If there is a BeanPostProcess object related to the Spring container that loads this Bean, execute the postProcessAfterInitialization() method.
  12. When you want to destroy a Bean, if the Bean implements the DisposableBean interface, execute the destroy() method.
  13. When you want to destroy a Bean, if the definition of the Bean in the configuration file contains the destroy-method attribute, execute the specified method.

Tell me about your understanding of Spring MVC?

Talking about this issue, we have to mention the previous eras of Model1 and Model2 without Spring MVC.

**Model1 era:** Many back-end programmers who learned Java late may not have been exposed to JavaWeb application development in the Model1 mode. In Model1 mode, the entire Web application is almost entirely composed of JSP pages, and only a small number of JavaBeans are used to handle database connection, access and other operations. In this mode, JSP is both the control layer and the presentation layer. Obviously, there are many problems with this model. For example, control logic and performance logic are mixed together, resulting in extremely low code reuse rate; another example is that the front-end and back-end are interdependent, making testing difficult and development efficiency extremely low.

Model2 Era: Friends who have studied Servlet and done related demos should understand the development model of Java Bean (Model) JSP (View) Servlet (Controller). This is the early Java Web MVC development model. Model is the data involved in the system, that is, dao and beans; View is used to display the data in the model, just for display; Controller sends user requests to Servlet for processing, returns the data to JSP and displays it to the user.

There are still many problems in the Model2 mode. The degree of abstraction and encapsulation of Model2 is far from enough. When using Model2 for development, it is inevitable to reinvent the wheel, which greatly reduces the maintainability and usability of the program. Reusability. As a result, many MVC frameworks related to Java Web development came into being, such as Struts2. However, because Struts2 is relatively cumbersome, with the popularity of Spring lightweight development framework, the Spring MVC framework appeared in the Spring ecosystem. Spring MVC is currently the best MVC framework. Compared with Struts2, Spring MVC is simpler and more convenient to use, has higher development efficiency, and Spring MVC runs faster.

MVC is a design pattern, and Spring MVC is an excellent MVC framework. Spring MVC can help us develop a more concise Web layer, and it is naturally integrated with the Spring framework. Under Spring MVC, we generally divide back-end projects into Service layer (processing business), Dao layer (database operations), Entity layer (entity classes), and Controller layer (control layer, returning data to the front-end page).

The simple schematic diagram of Spring MVC is as follows:

Talk about the working principle of Spring MVC

##Process description:

1. The client (browser) sends a request directly to the DispatcherServlet.

2.DispatcherServlet calls HandlerMapping based on the request information and parses the Handler corresponding to the request.

3. Parse to the corresponding Handler (which is what we usually call the Controller).

4.HandlerAdapter will call the real processor according to the Handler to process the request and execute the corresponding business logic.

5. After the processor finishes processing the business, it will return a ModelAndView object. Model is the returned data object, and View is the logical View.

6.ViewResolver will find the actual View based on the logical View.

7.DispatcherServlet passes the returned Model to View (view rendering).

8. Return the View to the requester (browser).

##What design patterns are used in the Spring framework?

  1. Factory design pattern: Spring uses the factory pattern to create bean objects through BeanFactory and ApplicationContext.
  2. Proxy design pattern: Implementation of Spring AOP functionality.
  3. Single case design pattern: Beans in Spring are singletons by default.
  4. Template method pattern: jdbcTemplate, hibernateTemplate and other classes ending with Template in Spring that operate on the database use the template pattern.
  5. Wrapper design pattern: Our project needs to connect to multiple databases, and different customers will access different databases according to their needs during each visit. This model allows us to dynamically switch between different data sources according to customer needs.
  6. Observer pattern: The Spring event-driven model is a classic application of the observer pattern.
  7. Adapter mode: Spring AOP enhancement or advice (Advice) uses the adapter mode, and Spring MVC also uses the adapter mode to adapt the Controller.

What is the difference between @Component and @Bean?

  1. The objects of action are different. The @Component annotation acts on classes, while the @Bean annotation acts on methods.
  2. @Component annotation is usually automatically detected and automatically assembled into the Spring container through class path scanning (we can use the @ComponentScan annotation to define the path to be scanned). The @Bean annotation is usually defined in the method marked with the annotation to generate this bean, telling Spring that this is an instance of a certain class and returned to me when I need to use it.
  3. @Bean annotation is more customizable than @Component annotation, and in many places beans can only be registered through @Bean annotation. For example, when a class that references a third-party library needs to be assembled into a Spring container, it can only be achieved through the @Bean annotation.

@Bean annotation usage example:

@Configurationpublic class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(); }}复制代码
Copy after login

The above code is equivalent to the following XML configuration:

 复制代码
Copy after login

The following example cannot be passed@ Implemented by Component annotation:

@Beanpublic OneService getService(status) { case (status) { when 1: return new serviceImpl1(); when 2: return new serviceImpl2(); when 3: return new serviceImpl3(); }}复制代码
Copy after login

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

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

  1. @Component注解。通用的注解,可标注任意类为Spring组件。如果一个Bean不知道属于哪一个层,可以使用@Component注解标注。
  2. @Repository注解。对应持久层,即Dao层,主要用于数据库相关操作。
  3. @Service注解。对应服务层,即Service层,主要涉及一些复杂的逻辑,需要用到Dao层(注入)。
  4. @Controller注解。对应Spring MVC的控制层,即Controller层,主要用于接受用户请求并调用Service层的方法返回数据给前端页面。

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

  1. 编程式事务:在代码中硬编码(不推荐使用)。
  2. 声明式事务:在配置文件中配置(推荐使用),分为基于XML的声明式事务和基于注解的声明式事务。

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

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

**ISOLATION_DEFAULT:**使用后端数据库默认的隔离级别,Mysql默认采用的REPEATABLE_READ隔离级别;Oracle默认采用的READ_COMMITTED隔离级别。

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

**ISOLATION_READ_COMMITTED: **Allow reading of data that has been submitted by concurrent transactions, which can prevent dirty reads, but phantom reads or non-repeatable reads may still occur

**ISOLATION_REPEATABLE_READ:**For the same field The results of multiple reads are consistent, unless the data is modified by the own transaction itself, which can prevent dirty reads and non-repeatable reads, but phantom reads may still occur.

**ISOLATION_SERIALIZABLE: **The highest isolation level, fully compliant with the ACID isolation level. All transactions are executed one after another in order, so that there is no possibility of interference between transactions. In other words, this level can prevent dirty reads, non-repeatable reads and phantom reads. But this will seriously affect the performance of the program. Normally this level is not used.

#What are the types of transaction propagation behaviors in Spring transactions?

Eight constants representing transaction propagation behavior are defined in the TransactionDefinition interface.

Support current transaction situation:

**PROPAGATION_REQUIRED: **If a transaction currently exists, join the Transaction; if there is currently no transaction, create a new transaction.

PROPAGATION_SUPPORTS:If a transaction currently exists, join the transaction; if there is currently no transaction, continue running in a non-transactional manner.

PROPAGATION_MANDATORY:If a transaction currently exists, join the transaction; if there is no transaction currently, throw an exception. (mandatory: mandatory).

If the current transaction is not supported:

##PROPAGATION_REQUIRES_NEW:Create a new transaction , if a transaction currently exists, suspend the current transaction.

PROPAGATION_NOT_SUPPORTED:Run in non-transactional mode. If a transaction currently exists, the current transaction will be suspended.

PROPAGATION_NEVER:Run in non-transactional mode, throwing an exception if a transaction currently exists.

Other situations:

PROPAGATION_NESTED:If a transaction currently exists, create a transaction to run as a nested transaction of the current transaction; if there is currently no transaction, Then this value is equivalent to PROPAGATION_REQUIRED.

End

I hope you can master these contents and continue to support me, thank you.

More related free learning recommendations:mysql tutorial(Video)

The above is the detailed content of collect! What Spring must master. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!