Spring, MVC, Boot framework summary

Spring is a lightweight development framework designed to improve the development efficiency of developers and the maintainability of the system.

What modules does Spring consist of?

  • spring core : Provides the basic components of the framework, including Inversion of Control (IOC) and Dependency Injection (DI) functions.
  • spring beans : Provides BeanFactory, which is a classic implementation of the factory pattern. Spring refers to the management object as Bean.
  • spring context : a context package built on the core package, which provides a framework for object access.
  • spring jdbc : Provides a JDBC abstraction layer, which eliminates cumbersome JDBC coding and database vendor-specific error code analysis, and is used to simplify JDBC.
  • spring aop : Provides an aspect-oriented programming implementation, allowing you to customize interceptors, pointcuts, etc.
  • spring Web : Provides integrated features for Web development, such as file upload, ioc container initialization using servlet listeners, and ApplicationContext for Web.
  • spring test : mainly provides support for testing, and supports unit testing and integration testing of Spring components using JUnit or TestNG.

@RestController vs @Controller

Controller returns a page

Using @Controller alone without @ResponseBody is generally used when you want to return a view. This situation is a more traditional Spring MVC application, which corresponds to the situation where the front and back ends are not separated.

@RestController returns data in JSON or XML format

But @RestController only returns objects, and the object data is directly written into the HTTP response (Response) in the form of JSON or XML. This situation is a RESTful Web service, which is also the most commonly used situation (front-end and back-end separation) in daily development.

@Controller +@ResponseBody returns JSON or XML data

If you need to develop RESTful Web services before Spring 4, you need to use @Controller combined with @ResponseBody annotations, that is, @Controller +@ResponseBody = @RestController (new annotations added after Spring 4).

@ResponseBody 注解的作用是将 Controller 的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到HTTP 响应(Response)对象的 body 中,通常用来返回 JSON 或者 XML 数据,返回 JSON 数据的情况比较多。

Spring IOC & AOP

Talk about my understanding of Spring IoC and AOP IoC

IoC (Inverse of Control: Inversion of Control) is a design idea, that is, the control of objects created manually in the program is handed over to the Spring framework to manage. IoC is also used in other languages ​​and is not unique to Spring. The IoC container is the carrier that Spring uses to implement IoC. The IoC container is actually a Map (key, value), and various objects are stored in the Map.

The interdependency between objects is handed over to the IoC container to manage, and the IoC container completes the injection of the objects. This simplifies application development to a large extent and frees 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/annotation, without considering 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, you may have to figure out the constructors of all the bottom classes of this Service every time. This may be Drive people crazy. If you use IoC, you only need to configure it, and then reference it where necessary, which greatly increases the maintainability of the project and reduces the difficulty of development.

In the Spring era, we generally used XML files to configure Beans. Later, developers felt that XML files were not good for configuration, so SpringBoot annotation configuration slowly became popular.

The initialization process of Spring IoC:
Insert picture description here

AOP

AOP (Aspect-Oriented Programming: Aspect-Oriented Programming) can encapsulate logic or responsibilities (such as transaction processing, log management, access control, etc.) that have nothing to do with the business but are called by business modules, so as to reduce the repetitive code of the system , Reduce the coupling degree between modules, and facilitate 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 Proxy to create proxy objects, and for objects that do not implement interfaces, JDK Proxy cannot be used for proxying. At this time, Spring AOP will use Cglib. At this time, Spring AOP will use Cglib 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 greatly simplifies the amount of code. It is also convenient when we need to add new functions, which also improves system scalability. AOP is used in scenarios such as log function and transaction management.

What is the difference between Spring AOP and AspectJ AOP?

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

Spring AOP has integrated AspectJ, and AspectJ 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 is little difference in performance between the two. However, when there are too many aspects, it is best to choose AspectJ, which is much faster than Spring AOP.

Spring bean

What are the scopes of beans in Spring?

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 都有不同的会话

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

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

There are two common solutions:

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

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

5.3 What is the difference between @Component and @Bean?

作用对象不同: @Component 注解作用于类,而@Bean注解作用于方法。
@Component通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中(我们可以使用 @ComponentScan 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。@Bean 注解通常是我们在标有该注解的方法中定义产生这个 bean,@Bean告诉了Spring这是某个类的示例,当我需要用它的时候还给我。
@Bean 注解比 Component 注解的自定义性更强,而且很多地方我们只能通过 @Bean 注解来注册bean。比如当我们引用第三方库中的类需要装配到 Spring容器时,则只能通过 @Bean来实现。
@Bean注解使用示例:

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

}

The above code is equivalent to the following xml configuration

The following example cannot be achieved by @Component.

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

What are the annotations for declaring a class as a Spring bean?

We generally use the @Autowired annotation to automatically assemble beans. If you want to identify a class as a class that can be used for @Autowired annotations to automatically assemble beans, you can use the following annotations:

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

Bean life cycle in Spring?

Bean 容器找到配置文件中 Spring Bean 的定义。
Bean 容器利用 Java Reflection API 创建一个Bean的实例。
如果涉及到一些属性值 利用 set()方法设置一些属性值。
如果 Bean 实现了 BeanNameAware 接口,调用 setBeanName()方法,传入Bean的名字。
如果 Bean 实现了 BeanClassLoaderAware 接口,调用 setBeanClassLoader()方法,传入 ClassLoader对象的实例。
与上面的类似,如果实现了其他 *.Aware接口,就调用相应的方法。
如果有和加载这个 Bean 的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessBeforeInitialization() 方法
如果Bean实现了InitializingBean接口,执行afterPropertiesSet()方法。
如果 Bean 在配置文件中的定义包含 init-method 属性,执行指定的方法。
如果有和加载这个 Bean的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessAfterInitialization() 方法
当要销毁 Bean 的时候,如果 Bean 实现了 DisposableBean 接口,执行 destroy() 方法。
当要销毁 Bean 的时候,如果 Bean 在配置文件中的定义包含 destroy-method 属性,执行指定的方法。

Spring MVC

Tell me about your understanding of Spring MVC?

Speaking of this issue, we have to mention the previous Model1 and Model2 eras without 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 并展示给用户。

There are still many problems in Model2 mode. The degree of abstraction and encapsulation of Model2 is far from enough. When using Model2 for development, wheels will inevitably be repeated, which greatly reduces the maintainability and reusability of the program. So many JavaWeb development-related MVC frameworks emerged such as Struts2, but Struts2 is relatively cumbersome. With the popularity of the 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, with 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 class), Controller layer (control layer, returning data to the foreground page).

The simple schematic diagram of Spring MVC is as follows:

Do you know how SpringMVC works?

The main components of Spring MVC?

(1) DispatcherServlet front controller (no need for programmer development)

Function: Receive requests and response results, which are equivalent to repeaters. With DispatcherServlet, the coupling between other components is reduced.

(2) HandlerMapping (no programmer development required)

Role: Find Handler according to the requested URL

(3) HandlerAdapter

Note: When writing the Handler, it must be written according to the rules required by the HandlerAdapter, so that the HandlerAdapter can execute the Handler correctly.

(4) Handler (need to develop by programmer)

(5) View Resolver ViewResolver (no programmer development required)

Function: Analyze the view and resolve it into a real view according to the logical name of the view

(6) View (requires programmers to develop jsp)

View is an interface, and its implementation class supports different view types (jsp, freemarker, pdf, etc.)

simply put:

The client sends a request -> the front controller DispatcherServlet accepts the client request -> finds the Handler corresponding to the processor mapping HandlerMapping to parse the request -> HandlerAdapter will call the real processor to process the request according to the Handler, and process the corresponding business logic -> The processor returns a model view ModelAndView -> view parser for analysis -> returns a view object -> front controller DispatcherServlet rendering data (Moder) -> returns the obtained view object to the user

Process description (important) :

客户端(浏览器)发送请求,直接请求到 DispatcherServlet。
DispatcherServlet 根据请求信息调用 HandlerMapping,解析请求对应的 Handler。
解析到对应的 Handler(也就是我们平常说的 Controller 控制器)后,开始由 HandlerAdapter 适配器处理。
HandlerAdapter 会根据 Handler来调用真正的处理器开处理请求,并处理相应的业务逻辑。
处理器处理完业务后,会返回一个 ModelAndView 对象,Model 是返回的数据对象,View 是个逻辑上的 View。
ViewResolver 会根据逻辑 View 查找实际的 View。
DispaterServlet 把返回的 Model 传给 View(视图渲染)。
把 View 返回给请求者(浏览器)

What design patterns are used in the Spring framework?

工厂设计模式 : Spring使用工厂模式通过 BeanFactory、ApplicationContext 创建 bean 对象。
代理设计模式 : Spring AOP 功能的实现。
单例设计模式 : Spring 中的 Bean 默认都是单例的。
模板方法模式 : Spring 中 jdbcTemplate、hibernateTemplate 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。
包装器设计模式 : 我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库。这种模式让我们可以根据客户的需求能够动态切换不同的数据源。
观察者模式: Spring 事件驱动模型就是观察者模式很经典的一个应用。
适配器模式 :Spring AOP 的增强或通知(Advice)使用到了适配器模式、spring MVC 中也是用到了适配器模式适配Controller。
......

Spring transaction

How many ways does Spring manage transactions?

编程式事务,在代码中硬编码。(不推荐使用)
声明式事务,在配置文件中配置(推荐使用)

Declarative transactions are divided into two types :

基于XML的声明式事务
基于注解的声明式事务

What are the isolation levels in Spring transactions?

Five constants representing the isolation level are defined in the TransactionDefinition interface:

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的隔离级别。所有的事务依次逐个执行,这样事务之间就完全不可能产生干扰,也就是说,该级别可以防止脏读、不可重复读以及幻读。但是这将严重影响程序的性能。通常情况下也不会用到该级别。

What kinds of transaction propagation behaviors in Spring transactions?

Support current affairs:

TransactionDefinition.PROPAGATION_REQUIRED: 如果当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。
TransactionDefinition.PROPAGATION_SUPPORTS: 如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行。
TransactionDefinition.PROPAGATION_MANDATORY: 如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常。(mandatory:强制性)

The situation where the current transaction is not supported:

TransactionDefinition.PROPAGATION_REQUIRES_NEW: 创建一个新的事务,如果当前存在事务,则把当前事务挂起。
TransactionDefinition.PROPAGATION_NOT_SUPPORTED: 以非事务方式运行,如果当前存在事务,则把当前事务挂起。
TransactionDefinition.PROPAGATION_NEVER: 以非事务方式运行,如果当前存在事务,则抛出异常。

Other situations:

TransactionDefinition.PROPAGATION_NESTED: 如果当前存在事务,则创建一个事务作为当前事务的嵌套事务来运行;如果当前没有事务,则该取值等价于TransactionDefinition.PROPAGATION_REQUIRED。

@Transactional(rollbackFor = Exception.class) annotation understand?

We know: Exception is divided into runtime exception RuntimeException and non-runtime exception. Transaction management is essential for enterprise applications. Even if there is an abnormal situation, it can also ensure data consistency.

When the @Transactional annotation is applied to a class, all public methods of the class will have this type of transaction attribute. At the same time, we can also use this annotation at the method level to override the class-level definition. If this annotation is added to the class or method, then the method in this class throws an exception, it will be rolled back, and the data in the database will also be rolled back.

If you don't configure the rollbackFor attribute in the @Transactional annotation, things will only roll back when they encounter RuntimeException. Adding rollbackFor=Exception.class can make things roll back when they encounter non-runtime exceptions.

JPA

How to use JPA to non-persistent a field in the database?

If we have the following class:

Entity(name="USER")
public class User {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private Long id;

    @Column(name="USER_NAME")
    private String userName;

    @Column(name="PASSWORD")
    private String password;

    private String secrect;

}

What if we want the secret field not to be persisted, that is, not to be stored in the database? We can use the following methods:

static String transient1; // not persistent because of static
final String transient2 = “Satish”; // not persistent because of final
transient String transient3; // not persistent because of transient
@Transient
String transient4; // not persistent because of @Transient

The latter two methods are generally used.

Spring commonly used annotations
SpringBoot knowledge points
Restful
named
MyBatis
concurrent programming

Guess you like

Origin blog.csdn.net/weixin_44379187/article/details/107914537