Introduction
Spring: Spring—>brings spring to the software industry
In 2002, Rod Jahnson first launched the interface21 framework, a prototype of the Spring framework.
On March 24, 2004, the Spring framework was redesigned and released the official version 1.0 based on the interface21 framework.
It’s hard to imagine Rod Johnson’s academic qualifications. He has a PhD from the University of Sydney, but his major is not computer science, but musicology.
Spring concept: Make existing technologies more practical. It is a hodgepodge in itself, integrating existing framework technologies
- It is a lightweight enterprise-level application framework
- The "one-stop" choice for enterprise application development, running through the presentation layer, business layer, and persistence layer
- advantage
- Low intrusion design
- Independent of various application servers
- Dependency injection feature makes component relationships transparent and reduces coupling
- Aspect-oriented programming features allow common tasks to be centralized
- Good integration with third-party frameworks
Spring architecture
Spring's two core mechanisms
- IOC: factory mode
- AOP: proxy mode
1. How to use IOC
- When creating a maven project, import relevant dependencies in pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xinxi2</groupId>
<artifactId>xinxi2-maven01</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring.version>5.2.5.RELEASE</spring.version>
</properties>
<dependencies>
<!-- mysql 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
</project>
- Create a cartridge entity class
package com.xinxi2.printor;
public class Printor {
private MoHe moHe; // 墨盒
private Paper paper; // 纸
// 目标对象
public void print(){
moHe.MoHe();
paper.Print();
}
public MoHe getMoHe() {
return moHe;
}
public void setMoHe(MoHe moHe) {
this.moHe = moHe;
}
public Paper getPaper() {
return paper;
}
public void setPaper(Paper paper) {
this.paper = paper;
}
}
- Create a cartridge interface
package com.xinxi2.printor;
public interface MoHe {
void MoHe();
}
- Create a paper interface
package com.xinxi2.printor;
public interface Paper {
void Print();
}
- Create a class to implement the ink cartridge interface, override the ink cartridge method, and output color ink cartridges
package com.xinxi2.printor;
public class ColorMoHelmpl implements MoHe{
@Override
public void MoHe() {
System.out.println("彩色墨盒");
}
}
- Create a class to implement the ink cartridge interface, override the ink cartridge method, and output a black ink cartridge
package com.xinxi2.printor;
public class BlackMoHelmpl implements MoHe{
@Override
public void MoHe() {
System.out.println("黑白墨盒");
}
}
- Create a class to implement the paper interface, override the paper method, and output A4 paper
package com.xinxi2.printor;
public class A4paperlmpl implements Paper{
@Override
public void Print() {
System.out.println("A4纸");
}
}
- Create the applicationContext.xml configuration file under the resources path
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<bean id="mohe1" class="com.xinxi2.printor.BlackMoHelmpl"></bean>
<bean id="A4paperimpl" class="com.xinxi2.printor.A4paperlmpl"></bean>
<bean id="printor" class="com.xinxi2.printor.Printor">
<property name="moHe" ref="mohe1"></property>
<property name="paper" ref="A4paperimpl"></property>
</bean>
</beans>
- Call the API and get the object from the IOC
@Test
public void test02(){
// 获取springContext上下文对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
Printor printor = (Printor)ac.getBean("printor");
printor.print();
}
- Output results
2. AOP
- AOP target
- Let's focus on business function processing
- AOP principle
- Decompose complex requirements into different aspects, and centrally solve common services between different objects and modules.
- Through the method of dynamic proxy, the extracted common code is "woven" into the business code to achieve enhanced processing of the original code,
as shown in the figure
- AOP related terms
- Aspect
- Advice (enhanced processing)
- Pointcut
- Join Point
- Target Object
- AOP proxy
- Weaving
Define entry point
Entry point: Simply put, it is the query condition of the connection point
<aop:config>
<aop:pointcut id="loggerPointcut"
expression="execution(public void print(..))"/>
<aop:aspect ref="sysLogger">
</aop:aspect>
</aop:config>
Examples of expression matching rules
expression="execution(public void print(..))"/>
- Various enhancements
Enhancement type | Features |
---|---|
Before | Pre-enhancement processing, weaving enhancement processing before the target method |
AfterReturning | Post-enhancement processing, weaving in the enhancement processing after the target method is executed normally (no exceptions occur) |
AfterThrowing | Exception enhancement processing, weaving in enhanced processing after the target method throws an exception |
After | Final enhancement processing, regardless of whether the method throws an exception, will be woven into the end of the target method. |
Around | Surround enhancement processing can be woven into the enhancement processing before and after the target method. Can control whether the target method is executed |
Weaving enhancements
Weaving: inserting enhancements at the entry point
- Demo: Create an entity class and add enhancement methods
package com.xinxi2.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component()
public class LoggerAdvic {
@Before("execution(public void wprk())")
public void before(JoinPoint jp){
System.out.println("前缀增强");
}
@AfterReturning("execution(public void wprk())")
public void retuRning(JoinPoint jp){
System.out.println("后置增强");
}
@AfterThrowing("execution(public void wprk())")
public void afterException(JoinPoint jp){
System.out.println("异常增强");
}
@Around("execution(public void wprk())")
public Object around(ProceedingJoinPoint pjp){
Object result = null;
try {
System.out.println("--------------------");
result = pjp.proceed(); // 执行方法
System.out.println("********************");
}catch (Throwable e){
e.printStackTrace();
}
System.out.println("环绕增强");
return result;
}
@After("execution(public void wprk())")
public void after(JoinPoint jp){
System.out.println("最终增强");
}
}
- Write the aop:config tag in applicationContext.xml
<aop:config>
<aop:pointcut id="loggerPointcut"
expression="execution(public void print(..))"/>
<aop:aspect ref="sysLogger">
<aop:before method="beforeLogger" pointcut-ref="loggerPointcut"></aop:before>
<aop:after-returning method="afterReturning" pointcut-ref="loggerPointcut" returning="obj"></aop:after-returning>
<aop:after-throwing method="afterException" pointcut-ref="loggerPointcut" throwing="e"></aop:after-throwing>
<aop:around method="around" pointcut-ref="loggerPointcut" ></aop:around>
<aop:after method="after" pointcut-ref="loggerPointcut"></aop:after>
</aop:aspect>
</aop:config>
Explain the above several enhancement methods
and exception throwing enhancement
- Features
- Weave in enhanced handling when a target object method throws an exception
- Flexible plug-and-play exception handling solution
<aop:config>
<aop:pointcut id="loggerPointcut"
expression="execution(public void print(..))"/>
<aop:aspect ref="sysLogger">
<!-- 异常增强 -->
<aop:after-throwing method="afterException" pointcut-ref="loggerPointcut" throwing="e"></aop:after-throwing>
</aop:aspect>
</aop:config>
final enhancement
- Features
- Regardless of whether the method runs normally or throws an exception, the enhancement will be woven into the end of the target method, that is, the enhancement will be executed.
- Similar to the finally code block in Java, it is usually used to release resources
- Flexible to plug and unplug
<aop:config>
<aop:pointcut id="loggerPointcut"
expression="execution(public void print(..))"/>
<aop:aspect ref="sysLogger">
<!-- 最终增强 -->
<aop:after method="after" pointcut-ref="loggerPointcut"></aop:after>
</aop:aspect>
</aop:config>
surround enhancement
- Features
- Enhancements can be woven into the target method before and after
- Can obtain or modify the parameters and return value of the target method
- Exceptions can be handled for the target method, and you can even decide whether the target method is executed or not.
<aop:config>
<aop:pointcut id="loggerPointcut"
expression="execution(public void print(..))"/>
<aop:aspect ref="sysLogger">
<!-- 环绕增强 -->
<aop:around method="around" pointcut-ref="loggerPointcut" ></aop:around>
</aop:aspect>
</aop:config>
constructor injection
- You can use the parameterized constructor
- Spring is an injection method for assigning values to properties through the constructor method.
- Properties can be assigned values when the object is initialized, which has good timeliness.
<bean id="daodao" class="com.xinxi2.bean.TSysUser">
<constructor-arg name="acccunt" value="王某某"></constructor-arg>
<constructor-arg name="address" value="王某"></constructor-arg>
</bean>
P-named injection
uses properties rather than sub-elements to configure Bean properties.
<bean id="唯一标识" class="类的全路径"
p:"属性1"="注入的值" p:"属性2"="注入的值" />
<bean id="唯一标识" class="类的全路径"
p:属性-ref="注入的Bean" />
When using the p namespace in the configuration file, you need to first add the declaration of the p namespace
xmlns:p="http://www.springframework.org/schema/p"
3. Spring form tags
3.1, Spring commonly used form tags
name | illustrate |
fm:form/ | Render form elements |
fm:input/ | Input box component label |
fm:password/ | Password box component label |
fm:hidden/ | Hide box component label |
fm:textarea/ | Multi-line input box component label |
fm:radiobutton/ | radio button component label |
fm:checkbox/ | Checkbox component label |
fm:select/ | Dropdown list component label |
fm:error/ | Display error information corresponding to form data verification |
fm:form tag
- modelAttribute
specifies the bound model attribute.
If this attribute is not specified, it will try to obtain the form attribute named "command" from the model by default. It is recommended to specify this attribute. - The target URL for action
-specified form submission
does not need to be specified, and the form will automatically be submitted with the URL of the form page as the target. Different operations can be distinguished through different request methods. - method
GET
POST
3.2, Label attributes
Attributes | describe |
path | Property path, indicating form object properties, such as account, realName, etc. |
cssClass | CSS style class name corresponding to the form component |
cssErrorClass | When an error is reported (server-side error) after submitting the form, the CSS style class used |
cssStyle | CSS styles corresponding to form components |
htmlEscape | Whether the bound form attribute value needs to convert HTML special characters, the default is true |
3.3, data verification
JSR 303 constraints
constraint | illustrate |
@Null | The annotated element must be null |
@NotNull | The annotated element must not be null |
@AssertTrue | The annotated element must be true |
@AssertFalse | The annotated element must be false |
@Min(value) | The annotated element must be a number whose value must be greater than or equal to the specified minimum value |
@Max(value) | The annotated element must be a number and its value must be less than or equal to the specified maximum value |
@DecimalMin(value) | The annotated element must be a number whose value must be greater than or equal to the specified minimum value |
@DecimalMax(value) | The annotated element must be a number and its value must be less than or equal to the specified maximum value |
@Size(max,min) | The size of the annotated element must be within the specified range |
@Digits(integer,fraction) | The annotated element must be a number and its value must be within an acceptable range |
@Past | The annotated element must be a date in the past |
@Future | The annotated element must be a future date |
@Pattern(value) | The annotated element must match the specified regular expression |