一、IOC___inverse of control
由面向对象中耦合问题---->面向接口(不方便修改)---->工厂模式(工厂内返回不同的对象还是需要修改)---->工厂+反射+配置---->IOC(控制反转inverse of control)
例如:
1、UserServiceImp实现了UserService接口中sayHello方法:
public class UserServiceImp implements UserService{
@Override
public void sayHello() {
System.out.println("hello spring !");
}
}
2、通过applicationContext.XML中配置ID
<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是等会需要使用时传入
<bean id="userService" class="com.zfy.ioc.demo1.UserServiceImp"></bean>
</beans>
3、对比普通方式和Spring方式创建对象
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo1 {
//普通方式创建UserService实现类对象
@Test
public void Demo1(){
UserService us = new UserServiceImp();
us.sayHello();
}
//Spring 通过XML配置+工厂创建对象
@Test
public void Demo2(){
//创建工厂
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
///创建对象
UserService us = (UserService) ac.getBean("userService");
us.sayHello();
}
}
二、DI___Dependency Injection
Spring在创建对象的时候,将对象所依赖的属性注入进去,(这个感觉有点酷炫,回头来看看源码)
1、当实现类UserServiceImp有自己的属性时候,如属性name:
public class UserServiceImp implements UserService{
private String name;
@Override
public void sayHello() {
System.out.println("hello spring "+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2、Spring 的依赖注入,依然在applicationContext.XML中,通过property中的name和value配置:
<bean id="userService" class="com.zfy.ioc.demo1.UserServiceImp">
<property name="name" value="张三"></property>
</bean>
3、对比普通方式和Spring方式对依赖属性的处理,普通方式需要改为新建实现类对象,并手动set属性值,而Spring方式代码无需任何修改
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDemo1 {
//普通方式创建UserService实现类对象,有属性时需new实现类对象
@Test
public void Demo1(){
// UserService us = new UserServiceImp();
UserServiceImp us = new UserServiceImp();
us.setName("张三");
us.sayHello();
}
//Spring 通过XML配置+工厂创建对象
@Test
public void Demo2(){
//创建工厂
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
///创建对象
UserService us = (UserService) ac.getBean("userService");
us.sayHello();
}
}