ioc:Inversion of Control 控制反转自动创建对象,例如Tomcat容器自动创建servlet等对象。
di:dependency injection 依赖注入提供对象名称即可实现该对象,利用反射机制。
maven配置了好久,这玩意一直报错,还慢死了,真的难用,淦!
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.7.RELEASE</version> </dependency>
//service01.java package com.faded828x.service; public class service01 { public service01() { } public void twoSum(int a, int b){ System.out.println(a+b); } }
//beans.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="sum1" class="com.faded828x.service.service01"/> </beans>
//testSum.java
package com.faded828x; import com.faded828x.service.service01; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class testSum { @Test public void testSum1(){ service01 service01 = new service01(); service01.twoSum(1, 2); } @Test public void testSum2(){ String config = "beans.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config); service01 sum1 = (service01) applicationContext.getBean("sum1"); sum1.twoSum(2,3); } }