手写spring ioc注解方式(包扫描)
2019-03-03 本文已影响0人
ssttIsme
package factory;
import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class AnnotationApplicationContext {
private Map<String,Object> beanMap=new HashMap<>();
public AnnotationApplicationContext() {
String pkg="project";
scanPackage(pkg);
}
private void scanPackage(final String pkg){
String pkgDir=pkg.replaceAll("\\.", "/");
URL url = getClass().getClassLoader().getResource(pkgDir);
File file=new File(url.getFile());
File fs[]=file.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
String fName=file.getName();
if(file.isDirectory()){
scanPackage(pkg+"."+fName);
}else{
//判断文件后缀是否为.
if(fName.endsWith(".class")){
return true;
}
}
return false;
}
});
for (File f : fs) {
String fName=f.getName();
//去除.class以后的文件名
fName=fName.substring(0,fName.lastIndexOf("."));
//将名字的第一个字母转为小写(用它作为key存储map)
String key=String.valueOf(fName.charAt(0)).toLowerCase()+fName.substring(1);
//构建一个类全名(包名.类名)
String pkgCls=pkg+"."+fName;
try {
//反射构建对象
Object obj = Class.forName(pkgCls).newInstance();
//将对象放到map容器
beanMap.put(key, obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public Object getBean(String key){
return beanMap.get(key);
}
public void close(){
beanMap.clear();
beanMap=null;
}
}
package project.controller;
public class CarController {
public void show(){
System.out.println("CarController");
}
}
package project.service.impl;
public class CarServiceImpl {
public void save(){
System.out.println("save car...");
}
}
package test;
import factory.AnnotationApplicationContext;
import project.controller.CarController;
import project.service.impl.CarServiceImpl;
public class TestApp {
public static void main(String[] args) {
AnnotationApplicationContext ctx=new AnnotationApplicationContext();
CarController obj = (CarController) ctx.getBean("carController");
System.out.println(obj);
obj.show();
CarServiceImpl obj2=(CarServiceImpl) ctx.getBean("carServiceImpl");
System.out.println(obj2);
obj2.save();
ctx.close();
}
}
运行结果
project.controller.CarController@52db59df
CarController
project.service.impl.CarServiceImpl@3ee969f8
save car...