Spring series
Spring Framework-1 (Foundation) Spring Framework-2 (IOC) Spring Framework-3 (IOC) Spring Framework-4 (AOP) Spring Framework-5 (JDBC Templates &Spring Transaction Management) Spring Framework-6 (SpringMvc) Spring Framework-7 (build SSM) Spring Framework-8 (SpringMVC2)
introduce
Spring is a layered (one-stop) lightweight open source framework. The core of Spring is Inversion of Control (IoC) and Aspect Oriented (AOP)
Why say stratified one-stop shop?
JavaEE is developed in three layers: WEB layer, business layer and persistence layer. In SSH integration framework s == Struts2, S == spring, h == Hibernate,spring one-stop development is not Struts2 and Hibernate, in Spring there are SpringMvc can replace Struts2, SpringJDBC can replace Hibernate. Equals a spring framework for rapid development of JavaEE applications. Not to mention lightweight, the entire Spring framework comes packaged with just over 1M memory. Spring is also not very expensive to run. That must be a lightweight framework.
Spring modules
Each module (or component) that makes up the Spring framework can exist on its own or be implemented in conjunction with one or more other modules. The functions of each module are as follows:
image
- Core container: The core container provides the basic functionality of the Spring framework. The main component of the core container is the BeanFactory, which is an implementation of the factory pattern. The BeanFactory uses an inversion of Control (IOC) pattern to separate the application’s configuration and dependency specifications from the actual application code.
- Spring Context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services, such as JNDI, EJB, E-mail, internationalization, validation, and scheduling capabilities.
- Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework through the configuration management feature. So, you can easily make any object managed by the Spring framework AOP enabled. The Spring AOP module provides transaction management services for objects in Spring-based applications. Using Spring AOP, you can integrate declarative transaction management into your application without relying on EJB components.
- Spring DAO: The JDBC DAO abstraction layer provides a meaningful exception hierarchy that can be used to manage exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write (such as opening and closing connections). Spring DAO’s JDBC-oriented exceptions follow a common DAO exception hierarchy.
- Spring ORM: The Spring framework inserts several ORM frameworks to provide ORM’s object-relational tools, including JDO, Hibernate, and iBatis SQL Map. All follow Spring’s common transaction and DAO exception hierarchies.
- Spring Web Module: The Web context module builds on the application context module and provides the context for Web-based applications. So, the Spring framework supports integration with Jakarta Struts. The Web module also simplifies handling multi-part requests and binding request parameters to domain objects.
- Spring MVC Framework: The MVC framework is a full-featured MVC implementation for building Web applications. With the policy interface, the MVC framework becomes highly configurable, and MVC accommodates a number of view technologies, including JSP, Velocity, Tiles, iText, and POI.
What is the function of IOC?
concept
IoC — Inverse of Control, Inverse of object creation to Spring! IOC can be used to solve the problem of high program coupling!
Inversion of control
Suppose I need to do a function where I need to call the Servic layer and then the DAO layer to fetch data. In traditional javaEE development I would simply go to new a service and then new a dao. But in the Spring framework, we transfer the rights to the new Service and the new DAO to the Spring framework. If I need to use it, I go directly to the Spring framework to find it. This is equivalent to giving my resource creation rights to the Spring framework, which is called inversion of control.
The decoupling
We just said that resource creation is in the hands of Sring, so let’s go to Spring for anything we need. The process is like the factory model. But what objects it needs to create in the Spring framework, it needs a configuration file. This configuration file tells Spring which resources need to be created.
For example, suppose I need to query the data display page in the database
When the program starts, the Spring framework finds the configuration file to create the resource, places the resource in another container, and starts to run. The front end requests the data, finds the Controller layer in Spring, then the Service layer, and then the DAO layer for data. Finally, the data is routed back to the Controller and displayed on the page. The Service is injected into the Controlller layer by Spring, and the DAO layer is injected into the Service layer by Spring. The process has a clear division of labor. Each layer has a role to play. A traditional development is to simply new in the servlet and look up the data, which is then returned to the interface. The servlet code becomes very bloated in case it operates on all the judgments and queries different tables. Not only is it slow, but it’s hard to look at the code when you’re done. So inversion of control can be used to decouple
What is AOP?
concept
- In the software industry, AOP is the abbreviation of Aspect Oriented Programming, meaning: Aspect Oriented Programming
- AOP is a programming paradigm that falls under the category of software and instructs developers how to structure their programs
- AOP was first proposed by the organization of the AOP Federation, which developed a set of specifications. Spring introduces AOP ideas into the framework and must comply with the AOP consortium’s specifications
- A technique for unified maintenance of program functions by means of precompilation and runtime dynamic proxies
- AOP is a continuation of OOP, a hot topic in software development, and an important content in Spring framework. It is a derivative paradigm of functional programming
- Using AOP, each part of the business logic can be isolated, thus reducing the degree of coupling between each part of the business logic, improving the reusability of the program, and improving the efficiency of development
In fact, AOP can not modify the source code under the premise of the program to enhance!!
The underlying implementation of AOP for the Spring framework
- Spring framework AOP technology is also the underlying use of proxy technology, proxy provides two ways
- Dynamic proxy based on JDK
Must be interface oriented; only classes that implement a concrete interface can generate proxy objectsCopy the code
- CGLIB based dynamic proxy
For classes that do not implement interfaces, proxies can also be generated, in the form of subclasses of that classCopy the code
- Spring’s traditional AOP uses different approaches to proxying, depending on whether a class implements an interface
- If you implement class interfaces, use JDK dynamic proxies for AOP
- If no interface is implemented, CGLIB dynamic proxies are used for AOP
JDK dynamic proxy
Note: You need to implement the class interface
Example: Suppose I have two jobs, job 1 and job 2.
Public interface Working {void wokingOne(); void WorkingTwo(); }Copy the code
Public class implements Working {@override public void wokingOne() {system.out.println (" implements task 1"); } @override public void WorkingTwo() {system.out.println (" WorkingTwo "); }}Copy the code
Ok, now I’m going to do task 1 and then task 2 and we’ll write it as:
public static void main(String[] args) { Working working = new WorkingImpl(); working.wokingOne(); 1 working.workingTwo (); // Do task 2}Copy the code
Ok, here’s the good part. I’m going to take a 10-minute break before I go back to task 2, but I can’t modify the source code. What to do? This is where our JDK dynamic proxy comes in. The code is as follows:
Start by writing a proxy utility class. Let’s take a 10-minute break before we do task 2 again
Public class MyProxyUtils {public static Working getProxy(final Working) {// Generate the Proxy object Working Proxy = (Working) Proxy.newProxyInstance(working.getClass().getClassLoader(), working.getClass().getInterfaces(), New InvocationHandler() {// Proxy object method a line, Invoke public Object invoke(Object proxy, Method Method, If ("WorkingTwo".equals(method.getName())) {if ("WorkingTwo".equals(method.getName())) { System.out.println(" rest 10 minutes "); Return method.invoke(working, args); }}); // return proxy; }}Copy the code
public static void main(String[] args) {
Working working = new WorkingImpl();
Working proxy = MyProxyUtils.getProxy(working);
proxy.wokingOne();
proxy.WorkingTwo();
}
Copy the code
The results of the operation can be imagined:
Do Task 1 take a 10-minute break to do Task 2Copy the code
CGLIB dynamic proxy
Note: No class interface is implemented
CGLIB is also a Java project, so using it requires the introduction of the CGLIB development JAR, since the CGLIB development package is already included in the Spring Framework core package. So go straight to the Spring core development package
Well, let’s do the same with the example above
Public class Working {public void wokingOne() {system.out.println (" do task 1"); } public void WorkingTwo() {system.out.println (" WorkingTwo "); }}Copy the code
New is the result of an object that calls task 1 and task 2 so I don’t have to say that. Let’s focus on using CGLIB to take a 10-minute break before doing a task without changing the source code.
Public static Working getProxy(){// create CGLIB core class Enhancer = new Enhancer(); // Set the parent class enhancer.setsuperclass (working.class); SetCallback (new MethodInterceptor() {@override public Object Intercept (Object obj, Method Method); Object[] args, MethodProxy MethodProxy) throws Throwable {if("WorkingTwo".equals(method.getName())){// Rest for 10 minutes System.out.println(" rest 10 minutes...") ); } return methodProxy.invokeSuper(obj, args); }}); Working Proxy = (Working) enhancer. Create (); return proxy; }Copy the code
public static void main(String[] args) {
Working working = new WorkingImpl();
Working proxy = MyCglibUtils.getProxy(working);
proxy.wokingOne();
proxy.WorkingTwo();
}
Copy the code
The final result is the same:
Do Task 1 take a 10-minute break to do Task 2Copy the code
Analysis of the
I briefly analyzed the two approaches to the underlying implementation of Spring AOP above: JDK dynamic proxy, CGLIB. In the Spring framework it automatically selects which approach to use. Use JDK dynamic proxies if you have an interface implementation class, and CGLIB if you don’t. This makes it much easier for us to modify things. Let’s say I need to log before I do task one again. I’m just going to write a section class and go straight to logging. Do not have to modify their own source code.
At the end
The author has just learned spring, recorded some knowledge points, sorted out their own understanding, if there is any mistake, I hope you put forward.