IoC
- IoC Inverse of Control 反转控制的概念,就是将原本在程序中手动创建UserService对象的控制权,交由Spring框架管理,简单说,就是创建UserService对象控制权被反转到了Spring框架
DI解释
- Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件。
例子:
在UserService中提供一个get/set的name方法,在beans.xml中通过property去注入
现在调用对象不用new了
Spring容器加载有3种方式
public class Lesson01 {
@Test
public void test1(){
//Spring容器加载有3种方式
//第一种:ClassPathXmlApplicationContext(最常用) ClassPath类路径加载:指的就是classes路径
//spring的配置文件路径直接放在src下
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//第二种方式:文件系统路径获得配置文件(绝对路径)
// ApplicationContext context = new FileSystemXmlApplicationContext("E:\\IdeaProject\\src\\beans.xml");
//第三种方式:使用BeanFactory(了解)
//String path = "E:\\IdeaProject\\src\\beans.xml";
//BeanFactory factory = new XmlBeanFactory(new FileSystemResource(path));
//IUserService user = (IUserService) factory.getBean("userService");
IUserService user = (IUserService) context.getBean("userService");
user.add();
}
}
BeanFactory和ApplicationContext对比
- BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean
- ApplicationContext是对BeanFactory扩展,提供了更多功能
- 国际化处理
- 事件传递
- Bean自动装配
- 各种不同应用层的Context实现
实例化Bean的三种方式
beans.xml
<!--装配bean的三种方式,所谓的装配bean就是在Xml写一个bean标签-->
<!--第一种方式:-->
<bean id="userService1" class="com.gyf.service.UserServiceImpl"></bean>
<!--第二种方式:通过静态工厂方法
spring的版本过低,3.0版本,使用jdk1.7-->
<bean id="userService2" class="com.gyf.service.UserServiceFactory1" factory-method="createUserService"></bean>
<!--第三种方式:通过实例工厂方法-->
<!--创建实例factory2 bean-->
<bean id="factory2" class="com.gyf.service.UserServiceFactory2"></bean>
<bean id="userService3" factory-bean="factory2" factory-method="createUserService">
test
public class Lesson03 {
@Test
public void test01(){
//new 对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml");
// IUserService userService1 = (IUserService) context.getBean("userService1");
//userService1.add();
//静态工厂
// IUserService userService2 = UserServiceFactory1.createUserService();
//IUserService userService2 = (IUserService) context.getBean("userService2");
//userService2.add();
//实例工厂
//1、创建工厂
//UserServiceFactory2 factory2 = new UserServiceFactory2();
//IUserService userService3 = factory2.createUserService();
IUserService userService3 = (IUserService) context.getBean("userService3");
userService3.add();
}
}
bean的作用域
类别 | 说明 |
singleton | 在Spring IoC容器中仅存在一个Bean实例,Bean以单例方式存在,默认值 |
prototype | 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时 ,相当于执行new XxxBean() |
<!--bean的作用域:singleton:单例,默认是单例;
prototype:多例-->
<bean id="userService" class="com.gyf.service.UserServiceImpl" scope="singleton"></bean>
依赖注入Bean属性(xml)
手动装配:
1、构造方法注入
2、属性setter方法注入
setter方法有两种注入,一般使用第一种直观
<bean id="user" class="com.gyf.spring.demo04.User"> <property name="username" value="zhangsan"></property> <property name="password" value="123456"></property> </bean> |
|
3、p命名空间注入【了解】
|
|
|