目前javaWeb开发领域,SpringMvc已经是绝大部分中小公司必选框架,那么springMvc是如何实现的呢。这里通过一个简单的小案例来演示一下。
首先看一下案例的结构图
目前springBoot项目比较流行,这里新建一个springBoot项目,先引入项目依赖
<?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.example</groupId>
<artifactId>refect</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>refect</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1、新建AopMethod注解,这个注解可以理解为RequestMapping
package com.example.refect.aop.core;
import java.lang.annotation.*;
/**
* 方法注解,这里类似RequestMapping
*/
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AopMethod {
String value() default "";
}
2、新建拦截器接口AopIntercepter,这里可以理解为SpringMvc拦截器
package com.example.refect.aop.core;
/**
* 拦截器
*/
public abstract class AopIntercepter {
abstract void before();
abstract void after();
}
3、新建拦截器实现类AopIntercepterImp
package com.example.refect.aop.core;
/**
* 拦截器实现
*/
public class AopIntercepterImp extends AopIntercepter {
@Override
public void before() {
System.out.println("调用前执行:before");
}
@Override
public void after() {
System.out.println("调用后执行:after");
}
}
4、新建aop核心接口 AopInter
package com.example.refect.aop.core;
import java.lang.reflect.Method;
import java.util.List;
/**
* aop核心接口
*/
public interface AopInter {
List<Method> getMethods(Class<?> annotation, String[] packagePath);
void invoke(Class<? extends AopIntercepter> clazz, Method method,Object args);
}
5、新建核心接口实现类AopCore
package com.example.refect.aop.core;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
/**
* aop核心实现,主要通过包路径扫描包下AopMethods的方法,获取方法集合
*
* 然后通过反射调用该方法
*/
public class AopCore implements AopInter{
@Override
public List<Method> getMethods(Class<?> annotationClass, String[] packagePath) {
Set<Class> classSet = new HashSet<>();
List<Method> functions = new ArrayList<>();
for(String path : packagePath){
String pack = path.replace(".","/");
try{
Enumeration<URL> url = getUrl(pack);
if(url==null){
return null;
}
while(url.hasMoreElements()){
URL u = url.nextElement();
String pro = u.getProtocol();
if("file".equals(pro)){
String filePath = URLDecoder.decode(u.getFile(),"UTF-8");
findAndAddClassesInPackageByFile(path,filePath,classSet);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
if(!classSet.isEmpty()){
for(Class clazz: classSet){
Method[] methods = clazz.getMethods();
for(Method method : methods){
AopMethod aopMethod = method.getAnnotation(AopMethod.class);
if(!StringUtils.isEmpty(aopMethod)){
functions.add(method);
}
}
}
}
return functions;
}
@Override
public void invoke(Class<? extends AopIntercepter> clazz, Method method,Object args) {
Method[] interMethods = clazz.getMethods();
Method before = null;
Method after = null;
for(Method m :interMethods){
if(m.getName().equals("before")){
before = m;
}else if(m.getName().equals("after")){
after = m;
}
}
try {
before.invoke(getClass().getClassLoader().loadClass(clazz.getName()).newInstance());
method.invoke(method.getDeclaringClass().newInstance(),args);
after.invoke(getClass().getClassLoader().loadClass(clazz.getName()).newInstance());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
private void findAndAddClassesInPackageByFile(String packagePath, String filePath, Set<Class> classSet) {
File fileDir = new File(filePath);
if(!fileDir.exists() || !fileDir.isDirectory()){
return;
}
File[] files = fileDir.listFiles(f->f.isDirectory() || f.getName().endsWith(".class"));
for(File file : files){
if(file.isDirectory()){
findAndAddClassesInPackageByFile(packagePath+"."+file.getName(),
file.getAbsolutePath(),classSet);
}else{
String className = packagePath+"."+file.getName().substring(0,file.getName().length()-6);
try {
classSet.add(Thread.currentThread().getContextClassLoader().loadClass(className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
}
}
private Enumeration<URL> getUrl(String packagePath){
try {
Enumeration<URL> enumeration = AopCore.class.getClassLoader().getResources(packagePath);
if(!enumeration.hasMoreElements()){
enumeration = Thread.currentThread().getContextClassLoader().getResources(packagePath);
if(!enumeration.hasMoreElements()){
return enumeration;
}
}
return enumeration;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
6、然后我们新建AopUser测试接口类,类似于Controller
package com.example.refect.aop.demo;
import com.example.refect.aop.core.AopMethod;
public class AopUser {
@AopMethod("/demo")
public String getStr(String str){
System.out.println("AopUser.getStr正在执行,"+str);
return str;
}
@AopMethod("/user")
public String getUser(String user){
System.out.println("AopUser.getUser:正在执行,"+user);
return user;
}
}
7、最后我们定义主方法Base,在主方法中调用AopUser中的接口方法
package com.example.refect.aop;
import com.example.refect.aop.core.AopCore;
import com.example.refect.aop.core.AopIntercepterImp;
import com.example.refect.aop.core.AopMethod;
import java.lang.reflect.Method;
import java.util.List;
/**
* 本包主要实现自定义拦截aop
*
* 简单实现 针对被注解的类中的方法被执行前,执行后调用自定义aop切面方法。
*
* 用户可以指定包路径 和 aop注解名称进行aop切面
*/
public class Base {
public static void main(String[] args) {
request("/user","张三");
}
private static void request(String mapping,Object args){
AopCore core = new AopCore();
List<Method> methodList = load();
for(Method method :methodList){
AopMethod annotation = method.getAnnotation(AopMethod.class);
String value = annotation.value();
if(value.equals(mapping)){
core.invoke(AopIntercepterImp.class,method,args);
}
}
}
private static List<Method> load(){
String[] paths = new String[]{"com.example.refect.aop.demo"};
List<Method> methodList = new AopCore().getMethods(AopMethod.class,paths);
return methodList;
}
}
执行主方法,控制台打印:
断点:
到此为止,简单的SpringMvc案例算是搭建完毕