1.使用xml方式注入对象
导入依赖:
<dependency> <groupId>dom4jgroupId> <artifactId>dom4jartifactId> <version>1.6.1version> dependency>
/** * Created by yz on 2018/6/3. */ public interface OrderService { public void addOrder(); }
/** * Created by yz on 2018/6/3. */ //@ExtService public class OrderServiceImpl implements OrderService { @Override public void addOrder() { System.out.println("使用Java反射机制初始化对象..."); } }
spring.xml
xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="orderService" class="com.yz.ioc.service.Impl.OrderServiceImpl"/> beans>
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.util.StringUtils; import java.io.InputStream; import java.util.List; /** * 自定义spring容器框架 xml方式实现 * Created by yz on 2018/6/3. */ public class ExtClassPathXmlApplicationContext { // xml读取路径地址 private String xmlPath; public ExtClassPathXmlApplicationContext(String xmlPath) { this.xmlPath = xmlPath; } public Object getBean(String beanId) throws Exception { if(StringUtils.isEmpty(beanId)){ return new Exception("bendId不能为空"); } // 1.解析xml,获取所有bean节点信息 Listreaderxml = readeXml(xmlPath); // 2.使用方法参数bend id查找配置文件中bean节点的id信息是否一致。 if(readerxml == null || readerxml.isEmpty()){ return new Exception("配置文件中,没有配置bean信息"); } String className = findByElementClass(readerxml, beanId); if(StringUtils.isEmpty(className)){ return new Exception("该bean对象没有配置class地址"); } // 3.获取class信息地址,使用反射机制初始化 return newInstance(className); } // 重构 public String findByElementClass(List readerxml,String beanId) throws Exception { for (Element element : readerxml) { // 获取属性信息 String xmlbeanId = element.attributeValue("id"); if(StringUtils.isEmpty(xmlbeanId)){ continue; } if(xmlbeanId.equals(beanId)){ String xmlClassPath = element.attributeValue("class"); return xmlClassPath; } } return null; } // 根据路径通过反射机制获取对象 public Object newInstance(String className) throws Exception { Class> classInfo = Class.forName(className); return classInfo.getDeclaredConstructor().newInstance(); } // 解析xml public List readeXml(String xmlPath) throws DocumentException { // 1.解析xml信息 SAXReader saxReader = new SAXReader(); Document document = saxReader.read(getResourcesAsStream(xmlPath)); // 2.读取节点下所有的子节点 Element rootElement = document.getRootElement(); // 3.获取根节点下所有的子节点 List elements = rootElement.elements(); return elements; } // 获取当前上下文 public InputStream getResourcesAsStream(String xmlPath){ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath); return inputStream; } }
import com.yz.ioc.ExtClassPathXmlApplicationContext; import com.yz.ioc.service.OrderService; /** * 测试ioc代码 * Created by yz on 2018/6/3. */ public class IOCTest { public static void main(String[] args) throws Exception { ExtClassPathXmlApplicationContext context = new ExtClassPathXmlApplicationContext("spring.xml"); OrderService orderService = (OrderService) context.getBean("orderService"); orderService.addOrder(); } }
2.使用注解方式注入对象 AOP IOC实现
spring.xml
xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.yz.ioc"/> beans>
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义@Service注解 注入bean容器 */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface ExtService { }
import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * 自定义@Resource注解 注入bean容器 */ @Target({TYPE, FIELD, METHOD}) @Retention(RUNTIME) public @interface ExtResource { }
/** * Created by yz on 2018/6/3. */ public interface OrderService { void addOrder(); }
/** * Created by yz on 2018/6/3. */ @ExtService public class OrderServiceImpl implements OrderService { @Override public void addOrder() { System.out.println("使用注解方式依赖注入..."); } }
/** * Created by yz on 2018/6/3. */ public interface UserService { void add(); }
import com.yz.ioc.annotation.ExtResource; import com.yz.ioc.annotation.ExtService; import com.yz.ioc.service.OrderService; import com.yz.ioc.service.UserService; /** * Created by yz on 2018/6/3. */ @ExtService public class UserServiceImpl implements UserService { @ExtResource private OrderService orderService; @Override public void add(){ orderService.addOrder(); } }
import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * 类相关的工具类 * Created by yz on 2018/6/3. */ public class ClassUtil { /** * 从包package中获取所有的Class * @param packageName * @return */ public static List> getClasses(String packageName){ //第一个class类的集合 List > classes = new ArrayList >(); //是否循环迭代 boolean recursive = true; //获取包的名字 并进行替换 String packageDirName = packageName.replace('.', '/'); //定义一个枚举的集合 并进行循环来处理这个目录下的things Enumeration dirs; try { 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"); //以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)){ //如果是jar包文件 //定义一个JarFile JarFile jar; try { //获取jar jar = ((JarURLConnection) url.openConnection()).getJarFile(); //从此jar包 得到一个枚举类 Enumeration entries = jar.entries(); //同样的进行循环迭代 while (entries.hasMoreElements()) { //获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); //如果是以/开头的 if (name.charAt(0) == '/') { //获取后面的字符串 name = name.substring(1); } //如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); //如果以"/"结尾 是一个包 if (idx != -1) { //获取包名 把"/"替换成"." packageName = name.substring(0, idx).replace('/', '.'); } //如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive){ //如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { //去掉后面的".class" 获取真正的类名 String className = name.substring(packageName.length() + 1, name.length() - 6); try { //添加到classes classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } } } catch (IOException e) { e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } /** * 以文件的形式来获取包下的所有Class * @param packageName * @param packagePath * @param recursive * @param classes */ public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List > classes){ //获取此包的目录 建立一个File File dir = new File(packagePath); //如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { return; } //如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { //自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); //循环所有文件 for (File file : dirfiles) { //如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { //如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { //添加到集合中去 classes.add(Class.forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } }
import com.yz.ioc.annotation.ExtResource; import com.yz.ioc.annotation.ExtService; import com.yz.ioc.uitl.ClassUtil; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.util.StringUtils; import java.io.InputStream; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * 自定义spring容器框架 注解方式实现 * Created by yz on 2018/6/3. */ public class ExtClassPathXmlApplicationContext { // 定义springbean容器 private ConcurrentHashMapbeans; // 扫包的范围 private String packageName; public ExtClassPathXmlApplicationContext(String xmlPath) throws Exception { // 初始化参数 beans = new ConcurrentHashMap<>(); this.packageName = getPackageName(xmlPath); initBeans(); initEntryField(); } // 初始化属性 private void initEntryField() throws Exception { // 1.遍历所有bena容器对象 for (Map.Entry entry : beans.entrySet()) { // 2.判断属性上面是否有加注解 Object object = entry.getValue(); inversionOfControl(object); } } public Object getBean(String beanId) throws Exception { System.out.println(beanId); if(StringUtils.isEmpty(beanId)){ throw new Exception("beanId参数不能为空"); } // 从spring容器获取bean Object object = beans.get(beanId); return object; } // 根据路径通过反射机制获取对象 public Object newInstance(Class> classInfo) throws Exception { return classInfo.getDeclaredConstructor().newInstance(); } // 初始化对象 public void initBeans() throws Exception { // 1.使用Java的反射机制扫包,获取当前包下所有的类 List > classes = ClassUtil.getClasses(packageName); // 2.判断类上是否存在注入bean的注解 ConcurrentHashMap classIsAnnotation = findClassIsAnnotation(classes); if(classIsAnnotation == null || classIsAnnotation.isEmpty()){ throw new Exception("该包下没有任何类加上注解"); } } // 判断类上是否存在注入bean的注解 public ConcurrentHashMap findClassIsAnnotation(List > classes) throws Exception { for (Class> classInfo : classes) { // 判断类上是否有注解 ExtService annotation = classInfo.getAnnotation(ExtService.class); if(annotation !=null){ // 获取当前类名,beanid 默认类名小写 String className = classInfo.getSimpleName(); String beanId = toLowerCaseFirstOne(className); // 通过反射机制创建对象 Object newInstance = newInstance(classInfo); beans.put(beanId,newInstance); continue; } } return beans; } //首字母转小写 public static String toLowerCaseFirstOne(String s){ if(Character.isLowerCase(s.charAt(0))) return s; else return (new StringBuilder()) .append(Character.toLowerCase(s.charAt(0))) .append(s.substring(1)).toString(); } // 读取xml中配置的包路径 public String getPackageName(String xmlPath) throws Exception { SAXReader saxReader = new SAXReader(); // 读取xml文件 Document document = saxReader.read(getResourcesAsStream(xmlPath)); // 读取节点 Element rootElement = document.getRootElement(); // 获取根节点下所有的子节点 List elements = rootElement.elements(); for (Element element : elements) { if(element.getName().equals("component-scan")){ // 获取扫包路径 Attribute attribute = element.attribute("base-package"); return attribute.getText(); } } return null; } public InputStream getResourcesAsStream(String xmlPath){ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath); return inputStream; } // 依赖注入 public void inversionOfControl(Object object) throws Exception { // 依赖注入实现原理 // 1.使用反射机制,获取当前类的所有属性 Class> classInfo = object.getClass(); Field[] fileds = classInfo.getDeclaredFields(); // 2.判断当前类属性是否存在注解 for (Field filed : fileds) { // 3.默认使用属性名称,查找bean容器对象 ExtResource extResource = filed.getAnnotation(ExtResource.class); if(extResource !=null){ // 获取属性名称 String beanId = filed.getName(); Object bean = getBean(beanId+"Impl"); if(bean != null){ // 允许访问私有属性 filed.setAccessible(true); // 属性赋值 filed.set(object,bean); } } } } }
/** * Created by yz on 2018/6/3. */ public class IOCTest { public static void main(String[] args) throws Exception { ExtClassPathXmlApplicationContext context = new ExtClassPathXmlApplicationContext("spring.xml"); // OrderService orderService = (OrderService) context.getBean("orderServiceImpl"); // orderService.addOrder(); UserService userService = (UserService) context.getBean("userServiceImpl"); userService.add(); } }