读书人

Spring初体验(2)多参数赋值

发布时间: 2012-09-02 21:00:34 作者: rapoo

Spring初体验(二)多参数赋值

我们在平时编写代码时常常用到给方法中多个参数的赋值,那么在Spring中是如何实现的呢。

?

案例:给方法中多个参数赋值

?

1、创建接口GreetingService,代码如下

?

?

package cn.csdn.service;public interface GreetingService {public void say();}

?

?

解析:这个接口中只有一个方法

?

2、创建接口实现类GreetingServiceImpl,代码如下

?

?

package cn.csdn.service;public class GreetingServiceImpl implements GreetingService {/**私有属性*/private String say;/**在定义一个私有的属性*/private String name;/** * IOC依赖注入的方式 * 2、通过构造器注入 * */public GreetingServiceImpl(String name,String say){this.name=name;this.say=say;}@Overridepublic void say() {System.out.println("你给"+name+"打的招呼是:"+say);}}

?

?

解析:这个接口实现类中有一个有参构造器,其中有两个参数,需要给这两个参数注入值

?

3、创建Spring配置文件applicationContext.xml

?

这里有两种方法为参数赋值:

?

1、利用索引方法,代码如下:

?

?

<?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-2.0.xsd">   <!-- 配置一个bean 指明bean id class property属性 value属性值 加载这个文件的时候 进行初始化 (需要根据bean的配置)-->    <bean id="greetingServiceImpl" name="code"><?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-2.0.xsd">   <!-- 配置一个bean 指明bean id class property属性 value属性值 加载这个文件的时候 进行初始化 (需要根据bean的配置)-->    <bean id="greetingServiceImpl" class="cn.csdn.service.GreetingServiceImpl">          <!-- 通过构造器的参数类型匹配方法进行注入 -->          <constructor-arg type="java.lang.String">       <value>Zhang_Di</value>     </constructor-arg>          <constructor-arg type="java.lang.String">       <value>你好!</value>     </constructor-arg>        </bean></beans>

?

注意:因为两个参数的类型都为String类型,所以在赋值时是按顺序赋值,若两参数类型不同,则会自动付给相应类型的值

?

3、两种方法的运行结果相同:

?

你给Zhang_Di打的招呼是:你好!

?

?

----------------------------

以上属个人理解,若有不足,请各位高手指点,谢谢..

?

读书人网 >软件架构设计

热点推荐