模拟Spring扫描注解类

1,编写注解类

import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {

	public String value();
}

 

2,扫描指定包下的所有.class结尾的类

        static List<String> list = new ArrayList<String>();
	static String packageDirName = "com.space".replace('.', '/'); 
	static StringBuffer buffer = new StringBuffer("com.space");
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		 
		  
	     Enumeration<URL> dirs=Thread.currentThread().getContextClassLoader().getResources(packageDirName);  
	   
	     while(dirs.hasMoreElements()){
	    	 URL url = dirs.nextElement();
             
	         String protocol = url.getProtocol();  
	         if ("file".equals(protocol)){//文件扫描
	             String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); 
	             File file = new File(filePath);
	             getClassName(file);
	         }  

	        if ("jar".equals(protocol)) {  
	            JarFile jar= ((JarURLConnection) url.openConnection()).getJarFile(); 
	            Enumeration<JarEntry> entries = jar.entries();//获取文件,需要递归处理文件夹

	        }
	     }
	     
	 
	     for(String str:list){
	    	 System.out.println(str);
	    	 Class<?> c = Class.forName(str);
	    	 boolean isAnno = c.isAnnotationPresent(Description.class);
	    	 if(isAnno){
	    		 Description d = c.getAnnotation(Description.class);
	    		 System.out.println(d.value());
	    	 }
	     }

	}
	
	public static void getClassName(File file) throws IOException{
		if(file.isDirectory()){
			File[] files =file.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					return pathname.getName().endsWith(".class")||pathname.isDirectory();
				}
			});
			for(File f:files){
				getClassName(f);
			}
			 
		}else{
			String name =file.getAbsolutePath();
			name = name.substring(name.lastIndexOf("com\\space")).replaceAll("\\\\", ".");
			name = name.substring(0, name.lastIndexOf("."));
			list.add(name);
		}
	}

 如果大家有更好的办法可以相互学习下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要定义一个自定义注解 `@RequiresPermissions`,用于标识需要授权访问的方法,例如: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface RequiresPermissions { String[] value(); // 权限值 } ``` 然后,我们需要实现一个切面,用于拦截被 `@RequiresPermissions` 标识的方法,并进行权限校验,例如: ```java @Component @Aspect public class PermissionCheckAspect { @Autowired private AuthService authService; @Around("@annotation(requiresPermissions)") public Object checkPermission(ProceedingJoinPoint joinPoint, RequiresPermissions requiresPermissions) throws Throwable { // 获取当前用户 User user = authService.getCurrentUser(); if (user == null) { throw new UnauthorizedException("用户未登录"); } // 获取当前用户的权限列表 List<String> permissions = authService.getUserPermissions(user); // 校验权限 for (String permission : requiresPermissions.value()) { if (!permissions.contains(permission)) { throw new ForbiddenException("没有访问权限:" + permission); } } // 执行目标方法 return joinPoint.proceed(); } } ``` 在切面中,我们首先通过 `AuthService` 获取当前用户及其权限列表,然后校验当前用户是否拥有被 `@RequiresPermissions` 标识的方法所需的所有权限,如果没有则抛出 `ForbiddenException` 异常,如果有则继续执行目标方法。 最后,我们需要在 Spring 配置文件中启用 AOP 自动代理,并扫描切面所在的包,例如: ```xml <aop:aspectj-autoproxy /> <context:component-scan base-package="com.example.aspect" /> ``` 这样,我们就通过 Spring AOP 和自定义注解模拟实现了似 Shiro 权限校验的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值