Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Tips for Spring Framework

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the tips of the Spring framework, has a certain reference value, friends in need can refer to. I hope you will learn a lot after reading this article. Next, let the editor take you to learn about it.

The Spring framework is a must in the interview. What exactly is in it? Let's have a look together. 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 designed to improve developers' development efficiency and system maintainability.

What we generally call the Spring framework is Spring Framework, which is a collection of many modules that can be easily used to assist us in development. These modules are core containers, data access / integration, Web, AOP (aspect-oriented programming), tools, messaging, and test modules. For example, Core component in Core Container is the core of all Spring components, Beans component and Context component are the foundation of IOC and DI, and AOP component is used to realize aspect-oriented programming.

Six characteristics of Spring:

Core technologies: dependency injection (DI), AOP, events (Events), resources, i18n, validation, data binding, type conversion, SpEL; testing: mock object, TestContext framework, Spring MVC testing, WebTestClient; data access: transactions, DAO support, JDBC,ORM, marshalling XML;Web support: Spring MVC and Spring WebFlux Web frameworks; integration: remoting, JMS,JCA,JMX, email, tasks, scheduling, caching Language: Kotlin,Groovy, dynamic language; list some important Spring modules

The following figure corresponds to the version of Spring 4.x, where the Portlet component of the Web module has been obsolete in the latest 5.x version, while the WebFlux component for asynchronous responsive processing has been added.

Spring Core: basic, it can be said that all other functions of Spring depend on this class library. It 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 transfers the control of objects created manually in the program to the Spring framework. IOC is also used in other languages and is not specific to Spring. IOC container is the carrier that Spring uses to implement IOC. IOC container is actually a Map (key, value), and various objects are stored in Map.

The interdependencies between objects are managed by the IOC container, and the object injection is completed by the IOC container. This can greatly simplify the development of applications and liberate 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, regardless of how the object is created. In a real project, a Service class may have hundreds or even thousands of classes as its underlying class. If we need to instantiate the Service, we may have to figure out the constructors of all the underlying classes of the Service every time, which may drive people crazy. If you use IOC, you just need to configure it and reference it where you need it, which greatly increases the maintainability of the project and reduces the difficulty of development.

In the era of Spring, we usually configure Bean through XML files, but later developers felt that it was not good to configure them with XML files, so Sprng 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, access control, etc.) that have nothing to do with business but are jointly invoked by business modules, so as to reduce the repetitive code of the system, reduce the coupling between modules, and is conducive to future scalability and maintainability.

Spring AOP is based on dynamic proxy, and if the object to be proxied implements an interface, Spring AOP will use JDK dynamic proxy to create a proxy object, while for objects that do not implement the interface, JDK dynamic proxy cannot be used. Instead, CGlib dynamic proxy is used to generate a subclass of the proxied object as a proxy.

Of course, you can also use the AspectJ,AspectJ that has been integrated into AspectJ,Spring AOP 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 to improve the expansibility of the system. AOP is used in scenarios such as logging, transaction management, and rights management.

The difference between Spring AOP and AspectJ AOP

Spring AOP is a run-time enhancement, while AspectJ is a compile-time enhancement. Spring AOP is based on Proxying, while AspectJ is based on bytecode operation (Bytecode Manipulation).

Spring AOP has integrated AspectJ,AspectJ, which is probably the most complete AOP framework in the Java ecosystem. AspectJ is more powerful than Spring AOP, but Spring AOP is relatively simple.

If we have fewer sections, 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 SpringAOP.

What is the scope of bean in Spring? Singleton: the only bean instance. Bean in Spring is a singleton by default. Prototype: a new bean instance is created for each request. Request: each HTTP request generates a new bean, which is valid only within the current HTTP request. Session: each HTTP request generates a new bean, which is valid only within the current HTTP session. Global-session: global session scope, which only makes sense in Portlet-based Web applications, is no longer available in Spring5. Portlet is a small Java Web plug-in that can generate fragments of semantic code, such as HTML. They are based on Portlet containers and can handle HTTP requests like Servlet. But unlike Servlet, each Portlet has a different session. Do you understand the thread safety issues of singleton bean in Spring?

Most of the time we don't use multithreading in the system, so few people pay attention to this problem. There is a thread problem in singleton bean, mainly because when multiple threads operate on the same object, there is a thread safety problem in writing to the object's non-static member variables.

There are two common solutions:

It is impractical to try to avoid defining variable member variables in bean objects. Define a ThreadLocal member variable in the class and store the required variable member variables in ThreadLocal (a recommended way).

Bean Lifecycle in Spring?

The Bean container finds the definition of Spring Bean in the configuration file. The Bean container leverages Java Reflection API to create an instance of Bean. If some attribute values are involved, use the set () method to set some attribute values. If Bean implements the BeanNameAware interface, call the setBeanName () method, passing in the name of Bean. If Bean implements the BeanClassLoaderAware interface, call the setBeanClassLoader () method, passing in an instance of the ClassLoader object. If Bean implements the BeanFactoryAware interface, call the setBeanClassFacotory () method, passing in an instance of the ClassLoader object. Similar to the above, if other * Aware interfaces are implemented, the corresponding methods are called. If there is a BeanPostProcessor object associated with the Spring container that loads the Bean, execute the postProcessBeforeInitialization () method. If Bean implements the InitializingBean interface, execute the afeterPropertiesSet () method. If the definition of Bean in the configuration file contains the init-method property, the specified method is executed. If there is a BeanPostProcess object associated with the Spring container that loads the Bean, execute the postProcessAfterInitialization () method. When you want to destroy the Bean, execute the destroy () method if the Bean implements the DisposableBean interface. When the Bean is to be destroyed, the specified method is executed if the definition of the Bean in the configuration file contains the destroy-method attribute.

Tell me what you know about Spring MVC?

When it comes to this issue, we have to mention the previous era of Model1 and Model2, which had no Spring MVC.

* * Model1 era: * * many back-end programmers who are late in learning Java may not have been exposed to JavaWeb application development in Model1 mode. In Model1 mode, the whole Web application is composed of almost all JSP pages, and only a small amount of JavaBean is used to deal with 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, the control logic and performance logic are mixed together, resulting in a very low code reuse rate; for example, the front-end and back-end are interdependent, difficult to test and extremely inefficient.

Model2 era: friends who have studied Servlet and done related Demo should understand the development mode of Java Bean (Model) + JSP (View) + Servlet (Controller), which is the early Java Web MVC development model. Model is the data involved in the system, that is, dao and bean;View are used to display the data in the model, only for display; Controller is to send user requests to Servlet for processing, return the data to JSP and show it to the user.

So many MVC frameworks related to Java Web development emerge as the times require, such as Struts2, but because Struts2 is relatively bulky, with the popularity of Spring lightweight development framework, Spring MVC framework appears in the Spring ecosystem. Spring MVC is the best MVC framework at present. Compared with Struts2,Spring MVC, it is simpler and more convenient to use, more efficient to develop, and faster to run Spring MVC.

MVC is a design pattern, and Spring MVC is an excellent MVC framework. Spring MVC can help us develop a cleaner Web layer, and it is inherently integrated with the Spring framework. Under Spring MVC, we generally divide the back-end projects into Service layer (processing business), Dao layer (database operation), Entity layer (entity class), and Controller layer (control layer, which returns data to the foreground page).

The simple schematic diagram of Spring MVC is as follows:

Talking about the working principle of Spring MVC

Process description:

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

2.DispatcherServlet calls HandlerMapping according to the request information to parse the corresponding Handler of the request.

3. Parse to the corresponding Handler (also known as the Controller controller).

4.HandlerAdapter invokes the real processor based on Handler to process the request and execute the corresponding business logic.

5. After the processor has finished processing the business, it returns 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 requestor (browser).

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

Factory design pattern: Spring uses factory mode to create bean objects through BeanFactory and ApplicationContext. Agent design pattern: the realization of Spring AOP function. Singleton design pattern: bean in Spring is singleton by default. Template method pattern: jdbcTemplate, hibernateTemplate and other classes in Spring that operate on the database ending in Template, they use the template pattern. Wrapper design pattern: our project needs to connect to multiple databases, and different customers will access different databases as needed during each visit. This mode allows us to dynamically switch different data sources according to the needs of our customers. Observer pattern: the Spring event-driven model is a classic application of the Observer pattern. Adapter pattern: the enhancement or Advice of Spring AOP uses the adapter pattern, and the adapter pattern adaptation Controller is also used in Spring MVC. What's the difference between @ Component and @ Bean? The action object is different. The @ Component annotation acts on the class, while the @ Bean annotation acts on the method. The @ Component annotation is usually automatically detected and assembled into the Spring container by classpath scanning (we can use the @ ComponentScan annotation to define the path to scan). The @ Bean annotation is usually defined to generate the bean in the method marked with the annotation, telling Spring that it is an instance of a class and giving it back to me when I need it. The @ Bean annotation is more customizable than the @ Component annotation, and in many places bean can only be registered through the @ Bean annotation. For example, when a class referencing a third-party library needs to be assembled into a Spring container, it can only be done through the @ Bean annotation.

Example of the use of @ Bean annotation:

@ Configurationpublic class AppConfig {@ Bean public TransferService transferService () {return new TransferServiceImpl ();}} copy the code

The above code is equivalent to the following XML configuration:

Copy the code

The following example cannot be achieved through the @ Component annotation:

@ Beanpublic OneService getService (status) {case (status) {when 1: return new serviceImpl1 (); when 2: return new serviceImpl2 (); when 3: return new serviceImpl3 ();}} what are the comments for bean where the copy code declares a class as Spring?

We usually use the @ Autowired annotation to automatically assemble bean. To identify a class as a bean that can be automatically assembled with the @ Autowired annotation, you can use the following annotations:

@ Component comment. General annotations that can mark any class as a Spring component. If a Bean doesn't know which layer it belongs to, you can annotate it with @ Component. @ Repository comment. The corresponding persistence layer, namely Dao layer, is mainly used for database-related operations. @ Service comment. The corresponding service layer, namely the Service layer, mainly involves some complex logic and needs to use the Dao layer (injection). @ Controller comment. The control layer of the corresponding Spring MVC, namely the Controller layer, is mainly used to accept user requests and call the methods of the Service layer to return data to the front-end page. How many ways can Spring transactions be managed? Programmatic transactions: hard-coded in code (not recommended). Declarative transactions: configured in configuration files (recommended), divided into XML-based declarative transactions and annotation-based declarative transactions. What are the isolation levels in Spring transactions?

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

* * ISOLATION_DEFAULT:** uses the default isolation level for backend databases, REPEATABLE_READ isolation level for Mysql by default, and READ_COMMITTED isolation level for Oracle by default.

* * the lowest isolation level of ISOLATION_READ_UNCOMMITTED:**, which allows you to read data changes that have not been committed, which may result in dirty reading, phantom reading, or unrepeatable reading.

* * ISOLATION_READ_COMMITTED:** allows reading data that has been committed by concurrent transactions, which can prevent dirty reads, but phantom or unrepeatable reads can still occur.

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

* * the highest isolation level of ISOLATION_SERIALIZABLE:** is fully subject to the isolation level of ACID. All transactions are executed one by one, so that interference between transactions is completely impossible, that is, this level prevents dirty reading, unrepeatable reading, and phantom reading. But this will seriously affect the performance of the program. This level is not usually used.

What are the transaction propagation behaviors in Spring transactions?

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

Support for the current transaction:

* * PROPAGATION_REQUIRED:** join a transaction if it currently exists, or create a new transaction if there is no transaction.

PROPAGATION_SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.

PROPAGATION_MANDATORY: if there is a transaction, join it; if there is no transaction, throw an exception. (mandatory: mandatory).

The current transaction is not supported:

PROPAGATION_REQUIRES_NEW: creates a new transaction and suspends the current transaction if it exists.

PROPAGATION_NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.

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

# other situations:

PROPAGATION_NESTED: if there is a transaction, a transaction is created to run as a nested transaction of the current transaction; if there is no transaction, this value is equivalent to PROPAGATION_REQUIRED.

Thank you for reading this article carefully. I hope it will be helpful for everyone to share the tips of the Spring framework. At the same time, I also hope that you will support us, pay attention to the industry information channel, and find out if you encounter problems. Detailed solutions are waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report