浅谈IOC
IOC(inversion of control)是Spring的核心,贯穿始终。所谓IOC 就是有Spring来控制对象的生命周期和对象间的关系。 传统开发模式:对象之间相互依赖 IOC开发模式:IOC控制对象之间的依赖
1.下载和导入jar包
[button color=“dark” icon=“glyphicon glyphicon-download-alt” url=“https://old.qwq.ro/usr/uploads/2021/01/3618899745.zip” type=“”]相关jar包下载[/button]
2.书写配置文件
Xml文件名字与位置任意,建议放到src目录下起名为applicationContext.xml
[collapse status=“false” title=“实体类”]
public class Product implements Serializable{
private static final long serialVersionUID = -5525888887336041659L;
private Integer pid;
private String pname;
private Integer price;
public Product() {
}
public Product(Integer pid, String pname, Integer price) {
this.pid = pid;
this.pname = pname;
this.price = price;
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
@Override
public String toString() {
return "Product{" +
"pid=" + pid +
", pname='" + pname + '\'' +
", price=" + price +
'}';
}
}
```[/collapse]
在xml中注册bean
<bean id="product" class="ro.qwq.entity.Product"></bean>
<!-- 通过set方法赋值 -->
<bean id="product2" class="ro.qwq.entity.Product">
<property name="pid" value="2"></property>
<property name="pname" value="玩具"></property>
<property name="price" value="100"></property>
</bean>
<!-- 通过构造赋值 -->
<bean id="product3" class="ro.qwq.entity.Product">
<constructor-arg index="0" value="3"></constructor-arg>
<constructor-arg index="1" value="冰淇淋"></constructor-arg>
<constructor-arg index="2" value="4"></constructor-arg>
</bean>
2.测试代码
public void test1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Product product = (Product) applicationContext.getBean("product");
product.setPid(1);
System.out.println(product);
}
@Test
public void test2(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Product product2 = (Product) applicationContext.getBean("product2");
System.out.println(product2);
}
@Test
public void test3(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Product product3 = (Product) applicationContext.getBean("product3");
System.out.println(product3);
}
IOC的好处
IOC不会对业务有很强的侵入性,是对象具有更好的可实用性,可重用性,可扩大性。 1.下降组件之间的耦合度。 2.提高产品的开发效力和质量。 3.统1标准,提高模块的复用性。 4.模块具有热插拔的特性。
IOC的总结
IOC控制反转: 创建对象实例的控制权从代码转移到IOC容器控制,实际就是xml文件控制,侧重于原理。 DI依赖注入: 说的是创建对象时,为这个对象注入属性值和其他对象实例,侧重于实现。