Spring preschool Foundation
rely on
1. Three elements of dependency composition
1.1 group id
1.2 project name
1.3 version number
2. Relationship between coordinates and local warehouse
Go to the local warehouse according to the coordinates. Find jar file
Here are all paths, pointing to the required files
3. If the dependency reports an error, first check whether the jar package of the local warehouse is correct
Transitivity of jar package dependency in maven
A depends on B and B depends on C. when importing a, BC will be imported
How?
1. Find the jar package file of the local warehouse according to the coordinates
2. After finding the jar package file, find * * pom file * *, and then find the dependencies in it
3. Then find the jar package according to the new coordinates and find * * pom file * *, circular operation
Find the coordinates in the dependency in the pom file, and then find the jar file
SHA1 algorithm
SHA-1 (English: Secure Hash Algorithm 1, Chinese Name: Secure Hash Algorithm 1) is a Cryptographic hash function . SHA-1 can generate a message called a message digest position(20byte )Hash value, which usually takes the form of 40 hexadecimal Number.
Hash related knowledge
Question 1: if the same hash algorithm is used for the same data, is the result the same?
Answer: same
hash is essentially a function with the same variables and the same results. If f (x) = x^2
Question 2: if the same hash algorithm is used for different data, are the results the same?
Answer: probably the same
Hash collision
Different hash algorithms with the same data results get the same results, which is called hash collision.
hash collision cannot be avoided in mathematics
Data transmission security assurance
If you tamper with the jar package during the jar package transmission, such as adding a Trojan virus.
Just compare the message summary before and after. If it is different, discard it and download it again
build tag
-
The plug-ins in build are indispensable
-
The path in mainClass must be consistent with the main startup class
-
If you copy the code, you can copy the dependencies content
maven common commands
1. clean instruction
Delete the target directory in the project, that is, delete the compiled file
2.compile instruction
Compile with maven tool java files – > class
3.install instruction
Package and deploy the developed project to form XXX Jar package file
effect:
1. If you are developing tools, the API / framework can be packaged into a jar package, and then other users can use the jar package through dependency
2. You can print the project into a jar package and deploy it directly. Users can access it directly through the website
Storage location:
-
There will be jar package files in the target directory
-
According to maven coordinates, jar packages will be generated in the local warehouse
Project release command
Note: the release environment of future projects is Linux system (pure dos command)
Command: Java - jar XXXXX Jar enter
The jar package generated by the above install is executed here. It has been renamed
Spring-IOC
Spring framework is an open source J2EE application framework initiated by Rod Johnson. It is a lightweight container for managing the life cycle of bean s.
-
J2SE java foundation J2EE java enterprise development J2ME mobile terminal development
-
bean: the objects managed by the spring container are called beans
-
Life cycle: object creation / object initialization / object execution business logic / object destruction
-
Lightweight container: Spring applies for a memory space in memory to store other objects
Interface oriented programming
Extract upward to simplify development. At this time, the interface is used to define the code of conduct
Advantages of interface oriented programming: it solves the coupling between attribute and method name, and can hardly modify attribute name in the future
Disadvantages of interface oriented programming: interface objects still point to subclass objects one by one, and the source code should be modified for later maintenance
Introduction to spring IOC
principle
IOC inversion of control is an idea. The creation right of an object is completed by the Spring framework. The container manages the life cycle of the object and performs dependency injection (DI) when necessary.
1.XML development
The Dog object is managed by the Spring container. Objects that are managed by containers are also called bean s
Description: in the early days of spring, configuration files were used to manage objects However, with the upgrading of software, annotation has become the mainstream Therefore, first complete the xml configuration file, and then complete the annotation
Content Description: xml files generally have fixed header tags
package demo2; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringGetDog { //Get Dog object from spring container //The Dog object is created and the configuration file is matched public static void main(String[] args) { System.out.println("**********"); //1. Read the Spring configuration file path String resource="spring.xml"; //2. Start the Spring container ApplicationContext context = new ClassPathXmlApplicationContext(resource); //3. Get object from container //Here, the reflection mechanism will be applied to create objects // Dog dog = (Dog) context.getBean("dog"); System.out.println("***************"); Dog dog2 = context.getBean(Dog.class); System.out.println(dog2); dog2.hello(); //Get object using reflection mechanism getDog(); } //The core principle of instantiation object, reflection mechanism public static void getDog(){ try { //Create objects with reflections //Reflection calls the object's parameterless construction Dog dog = (Dog) Class.forName("demo2.Dog").newInstance(); dog.hello(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
package demo2; public class Dog { public void hello(){ System.out.println("Puppy, spring Container management"); } public Dog() { System.out.println("wucan"); } }
XML file
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- id yes bean The unique identifier of the class name. Generally, the first letter of the class name is lowercase--> <bean id="dog" class="demo2.Dog"></bean> <!-- <bean id="cat" class="demo2.Cat"></bean>--> </beans>
Output results:
2. Steps for spring to create objects!!! Important!!!
- Specify the address of the Spring configuration file.
- Load the specified configuration file when the Spring container starts.
- When Spring scans the bean tag, load the attribute id and class
- According to the reflection mechanism, the instantiated object is reflected according to the path of class
- Spring internally maintains a large map < K, V > collection (container). The id in the bean is used as the key and the instantiated object is used as the value. Form: Map < id, instantiated object >
- Get the object from the Spring container by id or class type
- Calling business methods based on objects
3. Annotation development
component:
1. Entity class: class (object) managed by Spring container
2. Configuration class: equivalent to earlier xml configuration files
3. Test code: start the Spring container by annotation
package demo3; public class Cat { public Cat(){ System.out.println("cat Nonparametric structure of"); } public void hello(){ System.out.println("cat miaomiaomiao~"); } }
package demo3; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan("demo3")//Scans the current package and its sub packages according to the specified package path scan annotation @Configuration//Identifies that the current class is a configuration class, which is actually a configuration file public class SpringCatConfigure { /* * Method requirements: * 1.Must be public in common * 2.You must add a return value. The object of the return value is the object managed by the container * 3.The name of the method is the id of the bean * 4.The method must be identified with the @ Bean annotation before Spring can execute the method and identify the object to the Spring container * */ @Bean public Cat cat(){ return new Cat(); } }
package demo3; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringAnno { public static void main(String[] args) { ApplicationContext context= new AnnotationConfigApplicationContext(SpringCatConfigure.class); Cat cat = context.getBean(Cat.class); cat.hello(); } }
Multi instance pattern @ Scope in Spring
Objects in Spring are singleton by default
@Scope
In singleton mode, note that the location where the object is created is the longest line of code
The reason seems to be hunger
In the multi instance mode, just add a Scope annotation, and then execute the above code,
The code executed when creating the object is different from the singleton mode because it is lazy loading mode
Lazy loading in Spring
By default, when Spring starts, objects are created (analogical)
If lazy loading is enabled, the object will be created when the user starts it (similar to lazy loading)
After lazy loading, the object is created in the following line of code
Because the multi instance mode is lazy loading by default, lazy loading can only control the single instance mode
Spring life cycle
Phase division: object creation, initialization, business execution, and destruction
Annotation summary
@ComponentScan("demo3") //Scan annotations according to the specified package path @Configuration //Identifies that the current class is a configuration class @Bean //Identify the return value of the method and submit it to the Spring container for management @Scope("prototype") //Control single instance multiple instance mode @Lazy //Lazy loading @PostConstruct //Initialize the method and execute after constructing the method @PreDestroy ///Destroy method, execute after close
Spring steps!!!!
I summarized it according to the example
1. First write the classes you need to use, such as cat dog, etc
2. Write configuration file and configuration annotation@ Configureation@ComponentScan
Add @ Bean to the configuration file and hand over the classes written above to the Spring container for management
3. Write the test class and use the Spring container to execute the content you want to execute. First start the Spring container, load the configuration class (2), and then use the container to get the desired object, that is, get (1)
Spring dependency injection (DI)
Dependency injection case
A subclass of Dog class, which implements the Pet interface
package demo4; import org.springframework.stereotype.Component; @Component//Give this class to the Spring container management key: dog value: create an object using the reflection mechanism public class Dog implements Pet{ @Override public void hello() { System.out.println("Little leather dog, woof, woof!!!"); } public Dog(){ System.out.println("dog Nonparametric structure of"); } }
Pet interface
package demo4; public interface Pet { void hello(); }
User class, which injects the Pet interface
package demo4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.stereotype.Component; @Component //Give the User object to the Spring container for management public class User { /** * Injection: reference the objects in the Spring container!!! * @Autowired: Objects in containers can be injected * 1.Injection by type * If the injection type is an interface, its implementation class object will be found automatically for injection. In this example, the Dog class can be found directly * Note: generally, the internal interfaces of Spring framework are single implementation. (it can be realized under special conditions) * 2.Inject by name */ @Autowired //The pet interface is not handed over to Spring. If it is not injected, Spring cannot call this pet object private Pet pet; public void hello(){ pet.hello(); } }
Configuration class
package demo4; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @ComponentScan("demo4") @Configuration public class SpringConfigure { }
Implementation class
package demo4; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringDI { public static void main(String[] args) { ApplicationContext context= new AnnotationConfigApplicationContext(SpringConfigure.class); System.out.println("============================================"); User user = context.getBean(User.class); user.hello(); } }
be careful
1. After the class is managed by the Spring container, it will be placed in the Map. key: is the id of the class
value is an object created by the reflection mechanism. This process will execute the parameterless construction of the class
-
Injection: reference the objects in the Spring container!!!
@Autowired: you can inject objects in the container
1. Injection by type
If the injection type is an interface, its implementation class object will be found automatically for injection. In this example, the Dog class can be found directly
Note: generally, the internal interfaces of Spring framework are single implementation. (it can be realized under special conditions)
2. Inject by name: @ Autowired + @Qualifier
-
Pay attention to the comments of the above code to understand the code execution process.
-
Advantages of injection: there is no need to go to the new object. Annotations will directly help find the object implementing the class
Interface multi implementation case @ Qulifier
Under normal conditions, all interfaces in Spring are implemented in a single way. If multiple implementations are encountered, an error will be reported, as shown in the figure:
In the above, a pet is injected according to the type. At this time, it can be injected according to the name and Annotated:
Annotation summary
-
@ComponentScan("demo3") / / scan annotations according to the specified package path
-
@Configuration / / identifies that the current class is a configuration class
-
@Bean / / identifies the return value of this method and gives it to the Spring container for management
-
@Scope("prototype") / / control single instance and multi instance mode
-
@Lazy / / lazy loading
-
@PostConstruct / / initialize the method. Execute after constructing the method
-
@PreDestroy / / destroy the method and execute it after closing
-
@Component / / hand over the future objects of the current class to Spring for management
-
@Autowired / / inject by type
-
@Qualifier("cat") / / inject by name
MVC design idea
Traditional code structure:
If you write all the business code into one method. This leads to high coupling degree of later maintenance. In order to improve the scalability, the program is managed according to the MVC design idea.
MVC design idea description
M:Model data layer
5: View view layer
C:Control layer
The main purpose of MVC is to reduce code coupling, improve scalability and facilitate subsequent development
Back end "three-tier" code structure
Inspired by the design idea of MVC, in order to improve the scalability of the back-end code, the back-end code is generally divided into three layers.
- Controller layer: mainly interacts with the page @ controller
- Service layer: mainly implements the business logic @ service of the back end
- Dao layer / Mapper layer: it mainly interacts with the database, also known as the persistence layer @ Repository/@Mapper
Code structure description
-
Package name: mapper class 2, one interface UserMapper / one implementation class usermapperinpl
-
Package name: two service classes, one interface UserService / one implementation class UserServiceImpl
-
Package name: controller a class: UserController
**Knowledge Description: the called will generally have interfaces and implementation classes. The interface is for the convenience of being called and decoupled**
to configure
package demo5.configure; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("demo5") public class SpringConfig { }
Control layer
package demo5.Controller; import demo5.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @Controller public class UserControl { @Autowired private UserService userService; public void addUser(){ userService.addUser(); } }
Mapper layer interface
package demo5.mapper; public interface UserMapper { void addUser(); }
Mapper interface implementation class
package demo5.mapper; import org.springframework.stereotype.Repository; @Repository //Identify the persistence layer. This class is managed by the Spring container, which is also a @ Component. //key: userMapperImpl value: object public class UserMapperImpl implements UserMapper { @Override public void addUser() { System.out.println("Add users!!!"); } }
Service layer interface
package demo5.service; public interface UserService { void addUser(); }
Service layer interface implementation class, which is injected into Mapper layer
package demo5.service; import demo5.mapper.UserMapperImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService{ @Autowired //Inject mapper layer private UserMapperImpl userMapper; //IOC+DI decoupling @Override public void addUser() { userMapper.addUser(); } }
package demo5; import demo5.Controller.UserControl; import demo5.configure.SpringConfig; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Spring_MVC { public static void main(String[] args) { ApplicationContext context= new AnnotationConfigApplicationContext(SpringConfig.class); UserControl userControl = context.getBean(UserControl.class); userControl.addUser(); } }
Annotation summary
-
@ComponentScan("demo3") / / scan annotations according to the specified package path
-
@Configuration / / identifies that the current class is a configuration class
-
@Bean / / identifies the returned value of this method and gives it to the Spring container for management
-
@Scope("prototype") / / control single instance and multi instance mode
-
@Lazy / / lazy loading
-
@PostConstruct / / initialize the method. Execute after constructing the method
-
@PreDestroy / / destroy the method and execute it after closing
-
@Component / / hand over the future objects of the current class to Spring for management
-
@Autowired / / inject by type
-
@Qualifier("cat") / / inject by name
-
@Service / / identify the service layer
-
@Controller / / identify the controller layer
-
@Repository / / identifies the persistence layer
-
@Value ("${key}") / / assign a value to the property
-
@PropertySource(value = "classpath:/addUsers.properties", encoding = "UTF-8") / / load the configuration file at the specified location
Properties file assignment
#1. Data structure key=value #2. No quotation marks are required #3. Pay attention to redundant spaces #4. When the program reads files, ISO-8859-1 coding is adopted by default, and Chinese must be garbled name=bachelor
package demo6.Mapper; import com.sun.org.apache.bcel.internal.util.ClassPath; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Repository; @Repository @PropertySource(value = "classpath:/addUsers.properties",encoding = "UTF-8") //Spring loading configuration file key: name value: public class UserMapperImpl implements UserMapper { //Assign values to variables @Value("${name}") private String name; @Override public void addUser() { System.out.println("Add a user, here is usermapperimpl"+name ); } }
IOC-DI summary
IOC: Inversion of Control. The object is managed by the Spring container, which manages the life cycle of the object
DI: Dependency Injection, type / name injection, property injection for the current object (the property is also an object)
Summary: using IOC and DI can achieve loose coupling (decoupling) of code to a great extent
Spring-AOP
AOP code paving
Characteristics of things:
- Atomicity 2 Consistency 3 Isolation 4 persistence
Transaction description:
Add transaction control during addition, deletion and modification
Conclusion:
- If you edit according to the above codes, all the codes for adding / deleting / modifying operations must follow the above rules Then code redundancy
- UserService is tightly coupled with transaction control code Inconvenient for later expansion In the future, try to ensure the purity of the business as much as possible
Agency thought
Things that are inconvenient to do in the business layer but have to be done can be placed in the proxy object. Through this design, the problem of business layer coupling can be solved, and the proxy object looks the same as the real object. So users will not notice.
Analogy: 1 Takeout is also a typical agency idea 2 Game practice 3 letting agent
Dynamic agent JDK agent
configuration file
package com.jt.demo1.configre; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.jt.demo1") public class SpringConfigure { }
Build agent
package com.jt.demo1.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class JDKProxy { /* Get proxy object Parameter Description: public static object newproxyinstance (classloader, Class<?>[] interfaces, InvocationHandler h) 1.ClassLoader loader: Read real class data 2.Class<?>[] interfaces: Information required to pass interface Note: JDK agent requires the agent to either have an interface (itself is an interface) or implement an interface (implementation class) 3.InvocationHandler h: Executes when the proxy object executes the method */ public static Object getProxy(Object target){ //1 / get class loader ClassLoader classLoader = target.getClass().getClassLoader(); //2. Get the interface and make it clear that the class must have an interface, otherwise the array will be empty Class<?>[] interfaces = target.getClass().getInterfaces(); //Get proxy object return Proxy.newProxyInstance(classLoader,interfaces,getInvocationHandler(target)); } //Called when a proxy object executes a method public static InvocationHandler getInvocationHandler(Object target){ //Write dead code return new InvocationHandler() { @Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { System.out.println("Transaction start"); //Methods of executing real objects Object result = method.invoke(target, objects); System.out.println("End of transaction"); return result; } }; } }
Business interface
package com.jt.demo1.service; public interface UserService { void addUser(); }
Business implementation class
package com.jt.demo1.service; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("Add user"); } }
package com.jt.demo1; import com.jt.demo1.configre.SpringConfigure; import com.jt.demo1.proxy.JDKProxy; import com.jt.demo1.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext context= new AnnotationConfigApplicationContext(SpringConfigure.class); UserService userService = context.getBean(UserService.class); Class c = UserService.class; System.out.println(userService); //Get proxy object UserService proxy =(UserService) JDKProxy.getProxy(userService); System.out.println(proxy.getClass());//The calling class does not execute the methods inside System.out.println(proxy); //proxy.toString() calls the method by default, so it executes transactions proxy.addUser(); } }
Code output result:
JDK dynamic agent features
- Type name: class com sun. proxy.$ Proxy9
- Requirement: the delegate must be an interface or implementation class
- JDK proxy is an API provided by java natively, and no import package is required
- JDK dynamic proxy is often used in the source code of the framework
CGlib dynamic proxy
CGLib feature description
Historical reason: JDK dynamic proxy requires that there must be an interface. However, if some classes do not have an interface, the JDK proxy cannot be used to generate proxy objects Therefore, in order to fill the gap of knowledge, cglib agent is introduced
Problem Description: cglib dynamic proxy requires that proxy objects can be created with or without interfaces Question? How to ensure the "same" as the agent
Answer (feature): cglib dynamic proxy is required to inherit the agent A proxy object is a subclass of the agent
Role of dynamic agents
Note 1: generally, we decouple the highly coupled code in the business layer in the way of dynamic agent It makes the program more extensible (decoupling of business logic)
Description 2: Spring rules specifically for dynamic proxies It encapsulates a set of API s named AOP
AOP in Spring
AOP introduction
In the software industry, AOP is the abbreviation of Aspect Oriented Programming, which means: Aspect Oriented Programming, a technology to realize the unified maintenance of program functions through precompiled mode and dynamic agent during operation. AOP is the continuation of OOP, a hot spot in software development, an important content in Spring framework, and a derivative paradigm of functional programming. AOP can isolate each part of business logic, reduce the coupling between each part of business logic, improve the reusability of program, and improve the efficiency of development.
Summary: AOP in Spring uses proxy objects to extend methods without modifying the source code
Technical terms in AOP (difficulties)
1). Connection point: a method by which users can be extended
2). Entry point: the method of user's actual extension
3). Notice: specific implementation of extension method
4). Aspect: the process of applying notifications to pointcuts
AOP introduction case
1. Import jar package
org.springframework.boot
spring-boot-starter-aop
2 pointcut expression
* section = Pointcut expression + Notification method * 1.Entry point: it can be understood as a if judge * Judgment condition: pointcut expression * Rule: if the expression is satisfied, it is judged as true,Then execute the notification method * conversely, false,Do not execute notification method * 2.Pointcut expression: * 2.1 bean("Object Id") Intercept only one at a time (match) * 2.2 within("Package name.Class name ") * Note: the above two coarse-grained are matched by class * 2.3 execution(Return value type package name.Class name.Method name (parameter list) * 2.4 @annotation(Annotation package path) * * * * * */ @Pointcut("bean(userServiceImpl)") //Only match classes with userServiceImpl id @Pointcut("within(com.jt.demo2.service.*)") //Match all classes @Pointcut("execution(* com.jt.demo2.service..*.*(..))") //All classes, methods and arbitrary parameters in all packages under service. Is to scan all the data in the service @Pointcut("execution(* com.jt.demo2.service..*.delete(..))") //The method starting with delete does not fully satisfy the expression. So there is no pre notification, but the proxy object @Pointcut("@annotation(com.jt.demo2.anno.Haixin2022)")
3.demo
Custom annotation
package com.jt.demo2.anno; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD)//Annotations are used on methods @Retention(RetentionPolicy.RUNTIME)//Valid during operation public @interface Haixin2022 { //Annotations are used as markers }
Spring-AOP
package com.jt.demo2.aop; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component //Spring container management @Aspect //A facet class public class SpringAOP { /* * Aspect = pointcut expression + notification method * 1.Entry point: it can be understood as an if judgment * Judgment condition: pointcut expression * Rule: if the expression is satisfied, it is judged to be true, and the notification method is executed * Conversely, false does not execute the notification method * 2.Pointcut expression: * 2.1 bean("Object's Id '') intercepts only one at a time (matching) * 2.2 within("Package name Class name ") * Note: the above two coarse-grained are matched by class * 2.3 execution(Return value type package name Class name Method name (parameter list) * 2.4 @annotation(Annotation package path) * * * * * */ // @Pointcut("bean(userServiceImpl)") / / only match the class with id of userServiceImpl // @Pointcut("within(com.jt.demo2.service. *") / / matches all classes // @Pointcut("execution(* com.jt.demo2.service..*.*(..))") // All classes, methods and arbitrary parameters in all packages under service. Is to scan all the data in the service // @Pointcut("execution(* com.jt.demo2.service..*.delete(..))") // The method starting with delete does not fully satisfy the expression. So there is no pre notification, but the proxy object @Pointcut("@annotation(com.jt.demo2.anno.Haixin2022)") public void pointcut(){ } /* * Define notification method: * 1.The pre notification is executed before the target method is executed * 2.The post notification is executed after the target method is executed * 3.Exception notification is executed when an exception is thrown after the target method is executed * 4.Notice to be executed in the final notice * 5.Surround notification is a notification to be executed before and after the execution of the target method * * */ @Before("pointcut()") public void before(){//Before advice System.out.println("Hello~I'm an advance notice"); } }
configuration file
package com.jt.demo2.configre; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @ComponentScan("com.jt.demo2") @EnableAspectJAutoProxy //Make AOP in Spring work public class SpringConfigure { }
Interface
package com.jt.demo2.service; public interface UserService { void addUser(); void deleteUser(); }
Implementation class
package com.jt.demo2.service; import com.jt.demo2.anno.Haixin2022; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("Add user"); } @Override @Haixin2022 //Marking function public void deleteUser(){ System.out.println("delete user"); } }
Startup class
package com.jt.demo2; import com.jt.demo2.configre.SpringConfigure; import com.jt.demo2.service.UserService; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringAOPDemo { public static void main(String[] args) { ApplicationContext context= new AnnotationConfigApplicationContext(SpringConfigure.class); //Obtain the implementation class object according to the interface, but it matches the pointcut expression. For the convenience of subsequent extension, apo dynamically generates an agent UserService userService = context.getBean(UserService.class); //If it is an implementation class object, the method is not extended //If it is a proxy object, the method is extended aop valid System.out.println(userService.getClass()); userService.addUser(); } }
Visual metaphor of AOP
AOP is an abstract concept
Get annotation parameters dynamically
1. User defined annotation
package com.jt.demo2.anno; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD)//Annotations are used on methods @Retention(RetentionPolicy.RUNTIME)//Valid during operation public @interface Find { int id() default 0; //int id(); Method defaults to 0 }
2. Use notes
3. Requirements description
Print the id value in the annotation using the pre notification
package com.jt.demo2.aop; import com.jt.demo2.anno.Find; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Component //Spring container management @Aspect //A facet class public class SpringAOP { /* * Aspect = pointcut expression + notification method * 1.Entry point: it can be understood as an if judgment * Judgment condition: pointcut expression * Rule: if the expression is satisfied, it is judged to be true, and the notification method is executed * Conversely, false does not execute the notification method * 2.Pointcut expression: * 2.1 bean("Object's Id '') intercepts only one at a time (matching) * 2.2 within("Package name Class name ") * Note: the above two coarse-grained are matched by class * 2.3 execution(Return value type package name Class name Method name (parameter list) * 2.4 @annotation(Annotation package path) * */ // @Pointcut("bean(userServiceImpl)") / / only match the class with id of userServiceImpl // @Pointcut("within(com.jt.demo2.service. *") / / matches all classes // @Pointcut("execution(* com.jt.demo2.service..*.*(..))") // All classes, methods and arbitrary parameters in all packages under service. Is to scan all the data in the service // @Pointcut("execution(* com.jt.demo2.service..*.delete(..))") // The method starting with delete does not fully satisfy the expression. So there is no pre notification, but the proxy object @Pointcut("@annotation(com.jt.demo2.anno.Haixin2022)") public void pointcut(){ } /* * Define notification method: * 1.The pre notification is executed before the target method is executed * 2.The post notification is executed after the target method is executed * 3.Exception notification is executed when an exception is thrown after the target method is executed * 4.Notice to be executed in the final notice * 5.Surround notification is a notification to be executed before and after the execution of the target method * * */ @Before("pointcut()") public void before1(){//Before advice System.out.println("Hello~I'm an advance notice"); } /* * Knowledge points: * 1.If the pointcut expression is valid only for the current notification, it can be edited as follows * requirement: * Dynamically intercept the find annotation and obtain the id * Difficulties: * Get annotation object dynamically * Explanation: * 1.@annotation(find) Intercept the annotation of the type corresponding to the name of the find variable * 2.After matching the annotation, the annotation object is passed to find as a parameter * Advantages: * You can get the annotation content in one step to avoid reflecting code * * * * */ @Before("@annotation(find)") public void before2(Find find){//Before advice System.out.println("Hello~I'm an advance notice find's id"+ find.id()); } }
result:
Notification method
* Define notification method: * 1.The pre notification is executed before the target method is executed * 2.The post notification is executed after the target method is executed * 3.Exception notification is executed when an exception is thrown after the target method is executed * 4.Notice to be executed in the final notice *
explain:
The above four notifications are generally used to record the running status of the program, only for recording
Before advice
package com.jt.demo2.aop; import com.jt.demo2.anno.Find; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import java.util.Arrays; @Component //Spring container management @Aspect //A facet class public class SpringAOP { /* * Aspect = pointcut expression + notification method * 1.Entry point: it can be understood as an if judgment * Judgment condition: pointcut expression * Rule: if the expression is satisfied, it is judged to be true, and the notification method is executed * Conversely, false does not execute the notification method * 2.Pointcut expression: * 2.1 bean("Object's Id '') intercepts only one at a time (matching) * 2.2 within("Package name Class name ") * Note: the above two coarse-grained are matched by class * 2.3 execution(Return value type package name Class name Method name (parameter list) * 2.4 @annotation(Annotation package path) * * */ // @Pointcut("bean(userServiceImpl)") / / only match the class with id of userServiceImpl // @Pointcut("within(com.jt.demo2.service. *") / / matches all classes // @Pointcut("execution(* com.jt.demo2.service..*.*(..))") // All classes, methods and arbitrary parameters in all packages under service. Is to scan all the data in the service // @Pointcut("execution(* com.jt.demo2.service..*.delete(..))") // The method starting with delete does not fully satisfy the expression. So there is no pre notification, but the proxy object @Pointcut("@annotation(com.jt.demo2.anno.Haixin2022)") public void pointcut(){ } /* * Define notification method: * 1.The pre notification is executed before the target method is executed * 2.The post notification is executed after the target method is executed * 3.Exception notification is executed when an exception is thrown after the target method is executed * 4.Notice to be executed in the final notice * 5.Surround notification is a notification to be executed before and after the execution of the target method * Record the status of the program: * 1.class name / classpath of the target object * 2.Method name of the target object * 3.Parameter information of the method of the target object * 4.Gets the return value of the target object method * 5.Get the exception information of the execution error of the target object * * */ @Before("pointcut()") public void before1(JoinPoint joinPoint){//Before advice //1. Gets the type of the target Class targetClass = joinPoint.getTarget().getClass(); //2. Get the path of the target object String path = joinPoint.getSignature().getDeclaringTypeName(); System.out.println("targetclass(type)="+targetClass); System.out.println("path(route)="+path); //3. Get method name String methodName = joinPoint.getSignature().getName(); System.out.println("metnodname(Method name)="+methodName); //3. Get method parameters Object[] args = joinPoint.getArgs(); System.out.println("arg(parameter)="+ Arrays.toString(args)); } /* * Knowledge points: * 1.If the pointcut expression is valid only for the current notification, it can be edited as follows * requirement: * Dynamically intercept the find annotation and obtain the id * Difficulties: * Get annotation object dynamically * Explanation: * 1.@annotation(find) Intercept the annotation of the type corresponding to the name of the find variable * 2.After matching the annotation, the annotation object is passed to find as a parameter * Advantages: * You can get the annotation content in one step to avoid reflecting code * * * * */ // @Before("@annotation(find)") public void before2(Find find){//Before advice System.out.println("Hello~I'm an advance notice find's id"+ find.id()); } }
Output results:
**The video on the afternoon of December 24 was a big muddle, and the notes went around and around, which got me in
Holding day music
Around Advice
Notifications to be executed before and after the execution of the target method (highest utilization)
* */ @Before("pointcut()") public void before1(JoinPoint joinPoint){//Before advice //1. Gets the type of the target Class targetClass = joinPoint.getTarget().getClass(); //2. Get the path of the target object String path = joinPoint.getSignature().getDeclaringTypeName(); System.out.println("targetclass(type)="+targetClass); System.out.println("path(route)="+path); //3. Get method name String methodName = joinPoint.getSignature().getName(); System.out.println("metnodname(Method name)="+methodName); //3. Get method parameters Object[] args = joinPoint.getArgs(); System.out.println("arg(parameter)="+ Arrays.toString(args)); } /* * Knowledge points: * 1.If the pointcut expression is valid only for the current notification, it can be edited as follows * requirement: * Dynamically intercept the find annotation and obtain the id * Difficulties: * Get annotation object dynamically * Explanation: * 1.@annotation(find) Intercept the annotation of the type corresponding to the name of the find variable * 2.After matching the annotation, the annotation object is passed to find as a parameter * Advantages: * You can get the annotation content in one step to avoid reflecting code * * * * */
// @Before("@annotation(find)")
Public void before2 (find) {/ / pre notification
System.out.println("Hello ~ I'm the pre notice find's id" + find.id());
}
}
[External chain picture transfer...(img-or0Fca4c-1642764066236)] [External chain picture transfer...(img-OWgSdWcx-1642764066236)] Output results: [External chain picture transfer...(img-csW7KBsI-1642764066237)] **12 The video on the afternoon of June 24 was a big muddle, and the annotation circled around and around and got me in Holding day music ### Around Advice Notifications to be executed before and after the execution of the target method (highest utilization)