action层需要调用service层对象,service层又需要调用dao层的对象。一般情况而言就直接newXXX()使用就可以了,但 是这种方法会使程序的耦合性太强。当Action类中需要更换service方法时,就需要改动源代码。Spring框架就用IOC注入的方法帮我们解决 了这个问题。
示例代码(模拟WEB环境下):
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:context="http://www.springframework.org/schema/context" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- id是为class命名的key class是一个对象的地址。 --> <bean id="dao" class="com.wzh.dao.CashierDao"></bean> <bean id="service" class="com.wzh.service.CashierService"> <!-- name是需要注入的变量名 ref是需要引用的对象 --> <property name="cashierDao" ref="dao"></property> </bean> <bean id="action" class="com.wzh.action.CashierAction" scope="prototype"> <property name="cashierService" ref="service"></property> </bean> </beans>
action层:
public class CashierAction { //Action依赖Service private CashierService cashierService = new CashierService(); public CashierAction(){ System.out.println("正在创建CashierAction对象" + this.hashCode()); } public String action(){ getCashierService().service(); System.out.println("正在调用CashierAction.action方法"); return null; } public CashierService getCashierService() { return cashierService; } public void setCashierService(CashierService cashierService) { this.cashierService = cashierService; } }
service层:
public class CashierService { //依赖调用dao层 private CashierDao cashierDao = null; public CashierService(){ getCashierDao().save(); System.out.println("正在创建CashierService对象"+this.hashCode()); } public void service(){ System.out.println("调用CashierService.service方法"); } public CashierDao getCashierDao() { return cashierDao; } public void setCashierDao(CashierDao cashierDao) { this.cashierDao = cashierDao; } }
dao层:
public class CashierDao { public CashierDao(){ System.out.println("正在创建CashierDao对象"+this.hashCode()); } public void save(){ System.out.println("调用了CashierDao.save()方法"); } }
测试:
public class Test { public static void main(String[] args) { CashierAction cashierAction = new CashierAction(); cashierAction.action(); } }
结果:
时间: 2024-10-13 20:04:45