1. 程式人生 > >spring注入bean兩種方式(屬性注入,構造器注入)

spring注入bean兩種方式(屬性注入,構造器注入)

利用Spring的IOC實現簡單小程式,Spring推薦介面程式設計,這裡定義兩個介面:IDao,IService,以及它們的實現類IDaoImpl,IServiceImpl,程式碼如下:

package DAO;
public interface IDao {
public String sayHello(String name,String sex);
}

package DAO;
public class IDaoImpl implements IDao {
private String c_name;
private int age;
public IDaoImpl(String c_name, int age) {
super();
this.c_name = c_name;
this.age = age;
System.out.println("我叫 " + c_name + "今年"+age+"歲");
}

public String sayHello(String name, String sex) {
return "Hello " + name + sex;
}
}

package service;
public interface IService {

public void service( String name,  String sex);
}

package service;
import DAO.IDao;
public class IServiceImpl implements IService {
IDao dao;

public IDao getDao() {
return dao;
}
public void service(String name, String sex) {
System.out.println(dao.sayHello(name,sex));

}
public void setDao(IDao dao) {
this.dao = 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" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="daoImpl" class="DAO.IDaoImpl">
<constructor-arg index="1" name="age" value="22"></constructor-arg>
<constructor-arg index="0" name="name" value="Jim"></constructor-arg>
</bean>
<bean id="service" class="service.IServiceImpl">
<property name="dao" ref="daoImpl"></property>
</bean>
</beans>

寫一個測試程式碼的類Test:

package action;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import service.IService;

public class Test {
public static void main(String[] args) {
BeanFactory fac = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
IService is = (IService) fac.getBean("service");
is.service("Lucy","女士");
}
}

執行程式碼結果:

我叫 Jim今年22歲
Hello Lucy女士

此例子中用到了spring注入bean的常用兩種方式:依賴屬性注入(setter方法<property>...</property>),構造器方式注入(<constructor-arg >...<constructor-arg />)