Spring学习第二天:依赖注入方式之setter方法(1)

依赖注入的setter方法在开发中常用。

以往我们创建一个对象,会添加它的一些成员变量。并设置它的get,set方法。

比如,测试类中必须使用setName方法设置属性值。

例1(注 入字符串):

public class UserServiceImpl implements UserService {	
	private String name;	
	public void setName(String name) {
		this.name = name;
	}

}
<!--在test类中调用-->
public class Test_Spring {
	@Test
	public void run1() {
		UserServiceImpl us = new UserServiceImpl();
		us.setName("xxx");
		us.eat();
	}
}

现在我们用Spring的依赖注入方法,已经不需要在javabean中写get,set方法了。

public class UserServiceImpl implements UserService {
	private String name;
/*	public void setName(String name) {
		this.name = name;
	}*/
}

在applicationContext.xml中添加:

	<bean id="userService" class="com.Spring1.UserServiceImpl">
		<!-- 给成员属性赋值 value:属性值-->
		<property name="name" value="xxx"></property>
	</bean>
// Spring方法,依赖注入
@Test
public void run3() {
   // 创建工厂,加载核心配置
   ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
   UserService user = (UserService) ac.getBean("userService");
   user.eat();
  }
}

测试,注入成功!

例2:(复杂点的:注入对象)

一般我们在业务层是直接调用Dao里面的方法,如下:

public class CustomerServiceImpl {
	public void save() {
		System.out.println("我是业务层service");
		//原来的方式
		new CustomerDaoImpl().save();
	}
}

 下面我们使用Spring方法。首先要想使用业务层,先依赖customerDao。提供customerDao的成员属性,以及set方法。

有个这个类了,可以直接调用save方法了。

public class CustomerServiceImpl {
	//提供成员属性,提供set方法
	private CustomerDaoImpl customerDao;
	public void setCustomerDao(CustomerDaoImpl customerDao) {
		this.customerDao = customerDao;
	}
	public void save() {
		System.out.println("我是业务层service");
		//原来的方式
		//new CustomerDaoImpl().save();

		//Spring方式
		customerDao.save();
	}
}

依赖注入,在customerService中引入customerDao。下面就是把customerDao注入到customerService中。

<!-- 演示的依赖注入 -->
<bean id="customerDao" class="com.Spring1.CustomerDaoImpl">
</bean>
<bean id="customerService" class="com.Spring1.CustomerServiceImpl">
	<!-- value:是字符串,用ref是引用 -->
	<property name="customerDao" ref="customerDao"></property>
</bean>

测试,直接创建工厂。注:创建工厂的这个过程解析包含了先加载customerDao,后加载customerService。与例1同理

//Spring的方式
@Test
public void run5() {
	//下面这行创建工厂,加载配置文件,customerDao创建,customerService创建
	ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
	CustomerServiceImpl cs = (CustomerServiceImpl) ac.getBean("customerService");	
	cs.save();	
}

补充:

<bean id="customerService" class="com.Spring1.CustomerServiceImpl" />

当上面这行加载的时候,默认创建这个类的对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值