
IoC(控制反转):抽象来说是一种思想,我们开发过程中所有的对象都可以交给Spring进行管理,我们直接获取即可,不需要自己动手创建,即对象管理权的反转。具体来说IoC在Spring中是一个容器,一个管理对象的容器。
DI(依赖注入):Spring创建对象过程中,对对象所依赖的属性进行赋值,这个步骤就是依赖注入。
创建Maven项目并添加Spring核心依赖
1.2 添加Spring配置文件org.springframework spring-context5.1.17.RELEASE junit junit4.12 test
在resources目录下添加spring-config.xml配置文件
1.3 注册Bean
将需要被Spring管理的对象通过bean标签进行注册
1.4 获取Bean
创建测试类中Spring容器中获取已经注册的Bean
@Test
public void test01(){
// 加载IoC容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
// 从容器中获取Bean对象
UserBean userBean = applicationContext.getBean(UserBean.class);
System.out.println(userBean);
}
2. 获取Bean的方式
2.1 根据ID
ID只能声明一个
2.2 根据name
name可以声明多个,name=“u1,u2,u3” 表示会被拆分为3个name属性【拆分会根据 ‘,’ ‘;’ ’ ’ 空格 】
2.3 根据类型
通过类型获取时,如果容器中该类型有多个对象,则会报错。有两种解决方式:
- 通过组合条件获取
@Test
public void fun6(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// UserBean bean = ac.getBean(UserBean.class);
UserBean bean = ac.getBean("u1",UserBean.class);
bean.say();
}
- 通过设置primary属性,优先获取primary属性为true的对象。
通过构造方法注入,首先得提供对应的构造方法,既可以通过name 也可以通过index 来指定要赋值的参数。
3.2 设值注入
设值注入的属性必须提供对应的setter方法
3.2.1 不同类型的设值注入
// 对象 private Cat cat; // 数组 private String[] favorites; // List集合 private Listcats; // Map集合 private Map map; // 配置文件 private Properties props;
3.3 简化构造注入与设值注入篮球 爬山 逛街
root 123
在Spring配置文件中引入对应的名称空间
xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c"
3.4 工厂注入 3.4.1 静态工厂注入
package com.gupaoedu.factory;
import com.gupaoedu.pojo.UserBean;
import java.util.HashMap;
import java.util.Map;
public class StaticFactoryDemo {
public static Map hashMap ;
static {
hashMap = new HashMap();
hashMap.put("a1",new UserBean());
hashMap.put("a2",new UserBean());
hashMap.put("a3",new UserBean());
}
public static UserBean getInstance(){
return hashMap.get("a1");
}
}
3.4.1 动态工厂注入
package com.gupaoedu.factory;
import com.gupaoedu.pojo.UserBean;
public class DynamicFactoryDemo {
public UserBean getInstance(){
return new UserBean();
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)