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
然后进行测试
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注入属性的方式(修改配置文件代码)
public class HelloServiceTest {
public static void main(String[] args) {
ApplicationContext applicationContext= new ClassPathXmlApplicationContext("applicationContext.xml");
HelloService helloService=(HelloService)applicationContext.getBean("helloService");
helloService.saHello();
}
}
输出结果:HelloWorld
通过上面的例子我们可以的发现
IOC:IOC是将我们接口的控制权转交给Spring进行管理,解除了接口和实现类直接的耦合性
作者:499 ls 599