欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > spring中手写注解开发(创建对象篇)

spring中手写注解开发(创建对象篇)

2025/2/26 6:39:08 来源:https://blog.csdn.net/m0_73892800/article/details/145863854  浏览:    关键词:spring中手写注解开发(创建对象篇)

说明:

        在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集合中Map<String,Object> beanMap = new HashMap<String,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包的路径

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词