diff --git a/SpringFramework-ioc/READMD.md b/SpringFramework-ioc/READMD.md new file mode 100644 index 0000000..36c7297 --- /dev/null +++ b/SpringFramework-ioc/READMD.md @@ -0,0 +1,14 @@ +## IOC/DI(控制反转/依赖注入) +IOC/DI只解决一件事: 对象不new自己, 而是改由外部给他 + +#### 构造器注入和Setter注入: +1. 构造器在创建对象时注入, 能保证依赖非空, 适合必须的依赖, 官方推荐 +2. Setter在对象创建后注入, 不能保证依赖非空, 适合可选的依赖 + +#### 自动注入 autowire 取值: + +     取值:           含义: +1. no            不自动(默认) +2. byName   按属性名找Bean +3. byType    按类型找Bean +4. constructor    按构造器参数类型找 diff --git a/SpringFramework-ioc/src/main/java/com/ycjy/Main.java b/SpringFramework-ioc/src/main/java/com/ycjy/Main.java index 47ec47e..fd3da17 100644 --- a/SpringFramework-ioc/src/main/java/com/ycjy/Main.java +++ b/SpringFramework-ioc/src/main/java/com/ycjy/Main.java @@ -1,6 +1,7 @@ package com.ycjy; import com.ycjy.dao.DeptDao; +import com.ycjy.dao.DeptDaoImpl; import com.ycjy.service.DeptService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -10,7 +11,7 @@ public class Main { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); // 按照实现类取bean -// DeptDao deptDao = context.getBean("deptDao", DeptDao.class); +// DeptDaoImpl deptDao = context.getBean("deptDao", DeptDaoImpl.class); // deptDao.doSth(); // 按照接口取bean diff --git a/SpringFramework-ioc/src/main/java/com/ycjy/service/impl/DeptServiceImpl.java b/SpringFramework-ioc/src/main/java/com/ycjy/service/impl/DeptServiceImpl.java index 3a7d1cc..c4db164 100644 --- a/SpringFramework-ioc/src/main/java/com/ycjy/service/impl/DeptServiceImpl.java +++ b/SpringFramework-ioc/src/main/java/com/ycjy/service/impl/DeptServiceImpl.java @@ -8,7 +8,10 @@ public class DeptServiceImpl implements DeptService { private String test1; private DeptDao deptDao; - public DeptServiceImpl(DeptDao deptDao) { + public DeptServiceImpl() { + } + + public void setDeptDao(DeptDao deptDao) { this.deptDao = deptDao; } @@ -17,10 +20,6 @@ public class DeptServiceImpl implements DeptService { this.deptDao = deptDao; } - public void setDeptDao(DeptDao deptDao) { - this.deptDao = deptDao; - } - @Override public void doSth() { System.out.println(this.test1); diff --git a/SpringFramework-ioc/src/main/resources/applicationContext.xml b/SpringFramework-ioc/src/main/resources/applicationContext.xml index 3b653e0..aee906b 100644 --- a/SpringFramework-ioc/src/main/resources/applicationContext.xml +++ b/SpringFramework-ioc/src/main/resources/applicationContext.xml @@ -1,14 +1,37 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans.xsd" + default-autowire="byType" + default-autowire-candidates="*"> - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file