spring之DI屬性注入

DI:Dependency Injection 依賴注入,在Spring框架負責創建Bean對象時,動態的將依賴對象注入到Bean組件

(簡單的說,可以將另外一個bean對象動態的注入到另外一個bean中。)

 

【面試題】IoC和DI的區別 ?

DI和IoC是同一件事情,都是將對象控制權交給第三方(Spring)管理,只是站在不同角度而已。

即:Spring創建了Service、DAO對象,在配置中將DAO傳入Servcie,那麼Service對象就包含了DAO對象的引用。

實例練習:即在業務層的service對象注入dao屬性

applicationContext.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<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:spring創建的(UserDaoImpl)對象實例 
id 或name都是給對象起名字,
class:指定創建哪個對象的實例
-->

<bean name="userservice" class="com.spring.quickstart.UserServiceImpl">
<!--
property:注入的屬性
name:根據name來注入相應屬性setXxx方法裏面的xxx(小寫),
ref:引用哪個對象,把userdao這個對象賦值給了userservcie對象
    的一個成員變量dao(實際上是使用反射調用了setter方法賦值)
value:是賦值
  -->

  <property name="dao" ref="userdao">
  </property>
</bean>
<bean name="userdao" class="com.spring.quickstart.UserDaoImpl"/>
</beans>

表現層:

package com.spring.quickstart;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class SpringTest {
@Test
public void login(){

// UserService service = new UserServiceImpl();
//使用spring  ioc控制創建實例
//spring工廠,也稱spring容器,或者叫bean容器
ApplicationContext applicationContext = 
new FileSystemXmlApplicationContext("src/ApplicationContext.xml");
UserService service = (UserService) applicationContext.getBean("userservice");
service.login();
}
}

業務層:

package com.spring.quickstart;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class UserServiceImpl implements UserService {
private UserDao dao;
//需要使用setter方法注入屬性
public void setDao(UserDao dao) {
this.dao = dao;
}

public void login() {
// ApplicationContext applicationContext = 
// new FileSystemXmlApplicationContext("src/ApplicationContext.xml");
// ApplicationContext applicationContext = 
// new ClassPathXmlApplicationContext("ApplicationContext.xml");
// UserDao dao =(UserDao) applicationContext.getBean("userdao");
// UserDao dao = new UserDaoImpl();
dao.login();

}
public void reg(){
// ApplicationContext applicationContext = 
// new ClassPathXmlApplicationContext("ApplicationContext.xml");
// UserDao dao =(UserDao) applicationContext.getBean("userdao");
dao.reg();
}
}

持久層:

package com.spring.quickstart;


public class UserDaoImpl implements UserDao {


public void login() {
System.out.println("用戶登錄了......");
}


public void reg() {
System.out.println("用戶註冊......");
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章