【Spring实战】—— 5 设值注入

本篇主要讲解了Spring的最经常使用的功能——依赖注入。spring

注入的方式,是使用Getter Setter注入,平时大多的编程也都是使用这种方法。编程

  举个简单的例子,仍是表演者。this

  表演者有本身的属性,年龄或者表演的歌曲等等。还须要一些复杂的属性,好比乐器,每一种乐器会发出不一样的声音。spa

  下面看一下表演者Performercode

package com.spring.test.action1; public interface Performer { void perform() throws PerformanceException; }

  咱们本身定义一个钢琴演奏者,该表演者有年龄和歌曲,还有额外的一种乐器属性。orm

package com.spring.test.setter; import com.spring.test.action1.PerformanceException; import com.spring.test.action1.Performer; public class Instrumentalist implements Performer{ private String song; private int age; private Instrument instrument; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSong() { return song; } public void setSong(String song) { this.song = song; } public Instrument getInstrument() { return instrument; } public void setInstrument(Instrument instrument) { this.instrument = instrument; } public Instrumentalist(){} public void perform() throws PerformanceException { System.out.println("Instrumentalist age:"+age); System.out.print("Playing "+song+":"); instrument.play(); } }

  乐器的构造以下,依然使用接口方式:xml

package com.spring.test.setter; public interface Instrument { public void play(); }

  萨克斯实现该乐器接口blog

package com.spring.test.setter; public class Saxophone implements Instrument { public Saxophone(){} public void play() { System.out.println("TOOT TOOT TOOT"); } }

  以上就是基本的类的构造了。接口

  下面看一下Spring的配置文件:get

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
     <bean id="sax" class="com.spring.test.setter.Saxophone"/>
     <bean id="kenny" class="com.spring.test.setter.Instrumentalist">
         <property name="song" value="Jingle Bells" />
         <property name="age" value="25" />
         <property name="instrument" ref="sax" />
     </bean>
</beans>

  在配置文件中,能够发现,设值注入时,使用name来指定注入哪一个属性

  name的命名方式依据变量名称。

  1 首字母不区分大小写,其余部分与变量名称相同。

  2 注入的属性类型,能够是String , int , double , float等,当属性是String或int时,能够根据变量的类型自动转换。

  3 注入的是一个bean,则直接使用ref连接到另外一个bean便可。

  下面是应用上下文的代码:

package com.spring.test.setter; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.spring.test.action1.PerformanceException; public class test { public static void main(String[] args) throws PerformanceException { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); Instrumentalist performer = (Instrumentalist)ctx.getBean("kenny"); performer.perform(); } }

  执行结果以下:

Instrumentalist age:25 Playing Jingle Bells:TOOT TOOT TOOT
相关文章
相关标签/搜索