`

spring初步认识通过构造方法注入(二)

阅读更多

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 配置文件
<?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">
    
     <!--第一种方法: 通过构造器参数的索引位置匹配方法 索引位置从0开始
     <constructor-arg index="0">
       <value>redarmy_chen</value>
     </constructor-arg>
     <constructor-arg index="1">
       <value>你好!</value>
     </constructor-arg>
      -->

     <!-- 第二种方法:通过构造器的参数类型匹配方法进行注入  如果两个参数都是Stirng型的。程序赋值是顺序赋值-->
     <constructor-arg type="java.lang.String">  
       <value>你好!</value>
     </constructor-arg>
    
     <constructor-arg type="java.lang.String">
       <value>redarmy_chen</value>
     </constructor-arg>
    </bean>

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

 输出结果是:

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics