springIOC DI
2019-08-29 15:12
176 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/wendy_qgh/article/details/100136965
springIOC
1.springIOC 即控制反转,不用spring之前,创建一个对象需要自己new,用spring之后,只需在配置文件中配置。
1)对象的属性注入
- 类中有空的构造方法。使用<property name ="",value=""/>
- 类中有有参数的构造方法。
<constructor-arg name="" value=""></constructor-arg>
2)scope属性,默认singleton—单例模式,获取的是同一个对象。prototype----表示通过spring获取的对象不同。如:<bean id=’’ class=’'scope=‘singleton’>
3)parent属性,使用parent属性,可以继承类中的属性。还可以覆盖属性值。
public class Student{ private int id; private String name; private int age; } spring.xml配置文件 <bean id ="student" class="com.Student"> <property name ="id",value="1"/> <property name ="name",value="张三"/> <property name ="age",value="23"/> </bean> <bean id ="student1" class="com.Student" parent='student'> </bean>
输出打印student和student1,两个一样的值:id=1,name=张三,age=23。
注:输出是创建测试类,获取Spring容器,可通过id和运行时获取对象,然后打印:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext('spring.xml'); //2.通过运行时类获取对象 Student stu = applicationContext.getBean(Student.class);//运行时获取。 //Student stu = applicationContext.getBean("student");通过id获取,student为beanId; System.out.println(stu);
<bean id ="student" class="com.Student"> <property name ="id",value="1"/> <property name ="name",value="张三"/> <property name ="age",value="23"/> </bean> <bean id ="student1" class="com.Student" parent='student'> <property name ="name",value="李四"/> </bean>
这样可以覆盖,上面属性中的名字,输出student1对象则输出:id=1,name=李四,age=23.
4)P命名空间,属性注入,简化方法,
2.DI 依赖注入,在spring配置文件中,通过ref属性将其他bean赋给当前bean对象,是IOC的具体实现方式。
例如:
public class Classes{ private int id; private student stu1; public classes(){ } } public class Student{ private int id; private String name; private int age; } spring.xml中配置 <bean id ="class" class="com.Classes"> <property name ="id",value="1"/> <property name ="stu1",ref="student"/> </bean> <bean id ="student" class="com.Student"> <property name ="id",value="1"/> <property name ="name",value="张三"/> <property name ="age",value="23"/> </bean>
相关文章推荐
- IoC--Inversion of Contro and DI---Dependency Injection(Spring)
- Spring 第二天:ioc,di的概念,使用接口配合dj来编程
- Spring——IOC/DI理解
- 浅谈 SpringIOC/DI
- 【Spring笔记二】关于IOC和DI
- 【Spring】Spring的IOC(控制反转)/DI(依赖注入)原理(二):模拟Spring加载配置文件
- 用白话解释Spring中的 IoC 和 DI
- Spring的依赖注入(DI)和控制反转(IOC)
- spring入门学习-2、IOC、DI知识
- Spring源码分析之BOP/IOC/DI/AOP
- Spring--IoC---基本XML的DI---为集合属性赋值
- Spring IOC DI原理
- Spring--IoC--基于XML的DI-SPEL注入
- 使用EasyUI时的基础知识,关键词【List与Set,HashMap,Java访问数据库,Spring框架,SpringMVC,Spring的AOP,IOC|DI,Easyui,SpringDat】
- Spring--IoC--基于XML的DI-为应用指定多个配置文件-平等关系
- Spring(一)——IOC和DI的简单理解
- JAVA:Spring Ioc/AOP/DI/MVC/ 细看Springframework
- Spring用注解方式实现IOC和DI
- 【转】跟我一起学Spring 3(4)–深入理解IoC(控制反转)和DI(依赖注入)
- 关于spring的IOC和DI