网站后台页面设计教程,湘潭做网站价格 磐石网络,网络推广吧,网站首页被k怎么办说明#xff1a; 在spring底层中并不是我写的如此#xff0c;这篇只是我用我自己的方式实现了使用注解组件扫描并且 创建对象#xff0c;方法并不是很难#xff0c;可以看一看#xff0c;欢迎大佬评论 第一步#xff1a; 我们需要自己写一个注解#xff0c;我用的是idea…说明 在spring底层中并不是我写的如此这篇只是我用我自己的方式实现了使用注解组件扫描并且 创建对象方法并不是很难可以看一看欢迎大佬评论 第一步 我们需要自己写一个注解我用的是idea直接创建一个注解即可
//该注解说明它可以出现的范围value值为数组类型
//在使用注解时如果他的属性名是value时value可以省略
//如果属性值是数组类型且只有一个元素时大括号也可以省略
Target(
value{ElementType.TYPE,ElementType.FIELD}
)Rentation(RentationPolicy.RUNTIME)
public interface Component{
//String是属性类型一个是属性名String value() default ;
} 写这个注解就是以后扫描到这个注解就创建对象 第二步
创建三个类用于测试
Component(A)
public class A{public A(){System.out.println(A类被创建了);}
}
Component(B)
public class B{public B(){System.out.println(B类被创建了);}
}
Component(C)
public class C{public C(){System.out.println(A类被创建了);}
} 第三步
现在来编写需要运行的类
public class test{
public static void main(String[] args){//先创建一个map集合先将扫描到的对象暴漏创建放在map集合中MapString,Object beanMap new HashMapString,Object//给一个路径这里给的是类的根路径下的包具体路径看你自己类的位置String path com.mySpring.Annotation;//将路径里面的.换成/在正则表达式里面.表示所有所以不能直接写.//\.表达的是点要转义所以用\\.表示String realPath path.replaceAll(\\.,/);//获取你要扫描文件的绝对路径这里返回url对象URL url ClassLoader.getSystemClassLoader().getResource(realPath);String allPath url.getPath();//获取绝对路径下的所有文件File file new File(allPath);File[] files file.listFiles();//循环遍历文件Arrays.stream(files).forEach(f - {try{//获取类路径使用反射创建对象String className path.f.getName().split(\\.)[0];Class? aClass Class.forname(className);//判断类上是否有注解if(aClass.isAnnotationPresent(Component.class)){//获取Component组件对象Component component aClass.getAnnotation(Component.class);//获取id也就是value值String id component.value();//获取当前对象Object obj aClass.newInstance();//添加到map集合中beanMap.put(id,obj);}}catch(Exception e){e.printStackTrace();}});//最终查看一下map集合System.out.println(beanMap);}} 第四步
运行结果如图 注 在这里并没有写xml文件这一步只是模拟开局就已经给了path包的路径