---
title: "spring初步认识通过构造方法注入(二)"
author: "Doublecqw"
date: "2011-04-18T21:45:24Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2011-04-18T21:45:24Z"
id: 1007377
url: "https://doublecqw.iteye.com/blog/1007377"
---

public class GreetingServiceImpl  {  
 /\*\*私有属性\*/  
 private String say;  
 /\*\*在定义一个私有的属性\*/  
 private String name;  
 /\**  
  * IOC依赖注入的方式  
  * 2、通过构造器注入  
  * \*/  
 public GreetingServiceImpl(String name,String say){  
  this.name=name;  
  this.say=say;  
 }  
 @Override  
 public void say() {  
  System.out.println("你给"+name+"打的招呼是:"+say);  
 }  
}  
\----------------------------------------------  
applicationContext.xml 配置文件  
&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
&lt;beans xmlns="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)"  
  xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
  xsi:schemaLocation="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans) [http://www.springframework.org/schema/beans/spring-beans-2.0.xsd](http://www.springframework.org/schema/beans/spring-beans-2.0.xsd)"&gt;

   &lt;!-- 配置一个bean 指明bean id class property属性 value属性值 加载这个文件的时候 进行初始化 (需要根据bean的配置)--&gt;  
    &lt;bean id="greetingServiceImpl" class="cn.csdn.service.GreetingServiceImpl"&gt;  
      
     &lt;!--第一种方法： 通过构造器参数的索引位置匹配方法 索引位置从0开始  
     &lt;constructor-arg index="0"&gt;  
       &lt;value&gt;redarmy\_chen&lt;/value&gt;  
     &lt;/constructor-arg&gt;  
     &lt;constructor-arg index="1"&gt;  
       &lt;value&gt;你好！&lt;/value&gt;  
     &lt;/constructor-arg&gt;  
      --&gt;

     &lt;!-- 第二种方法：通过构造器的参数类型匹配方法进行注入  如果两个参数都是Stirng型的。程序赋值是顺序赋值--&gt;  
     &lt;constructor-arg type="java.lang.String"&gt;    
       &lt;value&gt;你好！&lt;/value&gt;  
     &lt;/constructor-arg&gt;  
      
     &lt;constructor-arg type="java.lang.String"&gt;  
       &lt;value&gt;redarmy\_chen&lt;/value&gt;  
     &lt;/constructor-arg&gt;  
    &lt;/bean&gt;

&lt;/beans&gt;  
 ------------------------------------------------------  
 测试：  
 @Test  
 public void test1(){  
  /\*\*加载spring容器  可以解析多个配置文件 采用数组的方式传递\*/  
  ApplicationContext ac = new ClassPathXmlApplicationContext(new String\[]{"applicationContext.xml"});  
     /\*\*IOC的控制反转体现\*/  
  GreetingService greetingService = (GreetingService) ac.getBean("greetingServiceImpl");  
  greetingService.say();  
 }

 输出结果是：

 你给你好！打的招呼是:redarmy\_chen