通过例子认识IOC并作出总结:
假设我们现在有一个接口HelloService,然后有一个实现类HelloServiceImpl
public interface HelloService {
public void saHello();
}
HelloServiceImpl
public class HelloServiceImpl implements HelloService {
@Override
public void saHello() {
System.out.println("Hello");
}
}
传统方法我们进行测试
public class HelloServiceTest {
public static void main(String[] args) {
HelloService helloService=new HelloServiceImpl();
helloService.saHello();
}
}
输出结果:Hello
如果我们使用IOC控制反转的话
现在配置文件(applicationContext.xml)中配置添加Bean
<bean id="helloService" class="com.service.impl.HelloServiceImpl"/>
然后进行测试
public class HelloServiceTest {
public static void main(String[] args) {
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");
HelloService helloService=(HelloService)applicationContext.getBean("helloService");
helloService.saHello();
}
}
拿到结果:Hello
那么当我实现类里面有属性的时候(修改HelloServiceImpl的代码,添加String属性)
public class HelloServiceImpl implements HelloService {
private String name;
@Override
public void saHello() {
System.out.println("Hello"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
进行测试
public class HelloServiceTest {
public static void main(String[] args) {
HelloServiceImpl helloService=new HelloServiceImpl();
helloService.setName("World");
helloService.saHello();
}
}
输出结果:HelloWorld
我们使用IOC的DI注入属性的方式(修改配置文件代码)
<bean id="helloService" class="com.service.impl.HelloServiceImpl">
<!--设置属性-->
<property name="name" value="World"></property>
</bean>
public class HelloServiceTest {
public static void main(String[] args) {
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");
HelloService helloService=(HelloService)applicationContext.getBean("helloService");
helloService.saHello();
}
}
输出结果:HelloWorld