Spring依赖注入方式

来源:互联网 发布:淘宝hd 2.6.1版本 编辑:程序博客网 时间:2024/05/17 06:02
package org.crazyit.app.service;public interface Person {//定义一个斧子的使用方法public void useAxe();}

package org.crazyit.app.service;public interface Axe {// Axe接口里面有个砍的方法public String chop();}

package org.crazyit.app.service.impl;import org.crazyit.app.service.Axe;public class StoneAxe implements Axe {@Overridepublic String chop() {return "石斧砍柴好慢!";}}

package org.crazyit.app.service.impl;import org.crazyit.app.service.Axe;import org.crazyit.app.service.Person;public class Chinese implements Person {private Axe axe;private Axe steel;// 设值注入所需的setter方法@Overridepublic void useAxe() {// 调用Axe的chop()方法// 标明Person对象依赖于axe对象System.out.println(axe.chop());System.out.println(steel.chop());}public void setAxe(Axe axe) {this.axe = axe;}public void setSteel(StellAxe steel) {this.steel = steel;}}

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans                        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd                        http://www.springframework.org/schema/context                        http://www.springframework.org/schema/context/spring-context-2.5.xsd                        http://www.springframework.org/schema/mvc                        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><!-- 配置Chinese实例,其实现类是Chinese --><bean id="chinese" class="org.crazyit.app.service.impl.Chinese"><!-- 将stoneAxe注给axe属性 --><property name="axe" ref="stoneAxe"></property><property name="steel" ref="steelAxe"></property></bean><!-- 配置stoneAxe实例,其实现类是stoneAxe --><bean id="stoneAxe" class="org.crazyit.app.service.impl.StoneAxe"></bean><!-- 配置SteelAxe的实例,其实现类是SteelAxe --><bean id="steelAxe" class="org.crazyit.app.service.impl.StellAxe"></bean></beans>

package lee;import org.crazyit.app.service.Person;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class BeanTest {public static void main(String[] args) throws Exception {// 创建Spring容器ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");// 获取Chinese实例Person p=ctx.getBean("chinese",Person.class);System.out.println(Person.class+"~~"+p);p.useAxe();}}

0 0