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命名空間注入【瞭解】