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包的路径