Spring核心配置檔案app_core.xml,配置檔案路徑存放在classpath下面的conf/spring目錄下,詳細配置
<?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 id="groupManagerService" class="org.lian.service.impl.GroupManagerServiceImpl"> <property name="groupManagerDao" ref="groupManagerDao"/> </bean> <bean id="groupManagerDao" class="org.lian.dao.impl.GroupManagerDaoImpl"> </bean> </beans>
Java類Service和Dao
public class GroupManagerServiceImpl implements GroupManagerService {
private GroupManagerDao groupManagerDao;
/*
* public GroupManagerDao getDao() { return groupManagerDao; }
*
* public void setDao(GroupManagerDao dao) { groupManagerDao = dao; }
*/
/**
*
* @description TODO
* @return
*/
@Override
public String getGroup() {
return groupManagerDao.getGroup();
}
public GroupManagerDao getGroupManagerDao() {
return groupManagerDao;
}
public void setGroupManagerDao(GroupManagerDao groupManagerDao) {
this.groupManagerDao = groupManagerDao;
}
}
public class GroupManagerDaoImpl implements GroupManagerDao {
@Override
public String getGroup() {
return "dao.getGroup()";
}
}
Spring IoC 配置起來還是比較容易,需要注意的一點是 此例中採用setter注入,這是一種常用的注入方式。bean中set方法名稱要和Spring配置檔案中bean property標籤中name屬性保持一致,在此例中
public void setGroupManagerDao(GroupManagerDao groupManagerDao) {
this.groupManagerDao = groupManagerDao;
}
<bean id="groupManagerService" class="org.lian.service.impl.GroupManagerServiceImpl"> <property name="groupManagerDao" ref="groupManagerDao"/> </bean>
與setter方法的形參名稱無關。
簡單 測試IoC的方式
public class App {
public static void main(String[] args) {
String classPath = "classpath*:conf/spring/app_*.xml";
// ApplicationContext context = new ClassPathXmlApplicationContext(
// new String[] { "services.xml", "daos.xml" });
ApplicationContext context = new ClassPathXmlApplicationContext(classPath);
GroupManagerService service = context.getBean(GroupManagerService.class);
System.out.println(service.getGroup());
}
}