控制反转的发展由来,是为了把控制权从class文件中脱离,从而更少的编译Java源文件。
1.main控制:运行简单,操作容易。缺点必须修改源代码来把握控制权
2.使用工厂模式:可以通过传入的参数来确定创建哪个对象,创建大部分对象不需要修改源代码
如果新增了对象,就必须工厂的判断代码,也不符合,封闭和开放原则
3.控制反转:只有源代码的修改才需要重新编译,可以完全将控制权交给配置文件
缺点:编码复杂,代码多的问题(spring)
面相对象的设计原则:
1.单一职责原则:一个类只做一件事情
2.封闭和开放原则:对修改关闭,对拓展开放
通过配置spring.xml的bean来实例化Dog对象
- <?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:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
-
- <!-- 相当也 Grade grade=new Grade()
- 并给这个对象赋值 grade.setGradeNo("1");
- -->
- <bean id="grade" class="cn.et.day20170522.spring.Grade">
- <property name="gradeNo" value="1"></property>
- <property name="gradeName" value="1610"></property>
- </bean>
-
-
-
- <bean id="stu" class="cn.et.day20170522.spring.Student">
- <property name="studentNo" value="1"></property>
- <property name="studentName" value="萌萌哒"></property>
- <property name="grade" ref="grade"></property>
- </bean>
-
- <bean id="stu1" class="cn.et.day20170522.spring.Student">
- <constructor-arg index="0" value="1"></constructor-arg>
- <constructor-arg index="1" value="小黑"></constructor-arg>
- <constructor-arg index="2" ref="grade"></constructor-arg>
- </bean>
-
- <bean id="stu2" class="cn.et.day20170522.spring.Student">
- <constructor-arg type="java.lang.String" value="1"></constructor-arg>
- <constructor-arg type="java.lang.String" value="小黑"></constructor-arg>
- <constructor-arg type="cn.et.day20170522.spring.Grade" ref="grade"></constructor-arg>
- </bean>
- </beans>
然后可以在Java获取到这个bean,并用它的父接口Animal来接收
- public class SpringTest {
- public static void main(String[] args) {
-
- ClassPathXmlApplicationContext cpxc=new ClassPathXmlApplicationContext("/cn/et/day20170522/spring/spring.xml");
-
-
-
-
-
-
-
-
- Student stu=(Student)cpxc.getBean("stu");
- System.out.println(stu.getGrade().getGradeName());
-
- Student stu1=(Student)cpxc.getBean("stu1");
- System.out.println(stu1.getGrade().getGradeName());
-
- Student stu2=(Student)cpxc.getBean("stu2");
- System.out.println(stu2.getGrade().getGradeName());
- }
- }
这样一来Spring的控制反转便把所有的控制权交给了配置文件,我们完全可以在spring.xml文件中修改bean的class属性来控制创建Animal的其它对象
控制反转的发展由来,是为了把控制权从class文件中脱离,从而更少的编译Java源文件。
1.main控制:运行简单,操作容易。缺点必须修改源代码来把握控制权
2.使用工厂模式:可以通过传入的参数来确定创建哪个对象,创建大部分对象不需要修改源代码
如果新增了对象,就必须工厂的判断代码,也不符合,封闭和开放原则
3.控制反转:只有源代码的修改才需要重新编译,可以完全将控制权交给配置文件
缺点:编码复杂,代码多的问题(spring)
面相对象的设计原则:
1.单一职责原则:一个类只做一件事情
2.封闭和开放原则:对修改关闭,对拓展开放
通过配置spring.xml的bean来实例化Dog对象
然后可以在Java获取到这个bean,并用它的父接口Animal来接收
这样一来Spring的控制反转便把所有的控制权交给了配置文件,我们完全可以在spring.xml文件中修改bean的class属性来控制创建Animal的其它对象