Java依赖注入方式
Posted www
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java依赖注入方式相关的知识,希望对你有一定的参考价值。
构造方法注入
application.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.xsd"> <bean id = "Orange" class="com.wzh.fruit.impl.Orange"></bean> <bean id = "Apple" class="com.wzh.fruit.impl.Apple"></bean> <bean id = "personApple" class="com.wzh.person.Person"> <constructor-arg ref="Apple"></constructor-arg> </bean> <bean id = "personOrange" class="com.wzh.person.Person"> <constructor-arg ref="Orange"></constructor-arg> </bean> </beans>
Fruit.java
package com.wzh.fruit; public interface Fruit { public String getFruit(); }
Apple.java
package com.wzh.fruit.impl; import com.wzh.fruit.Fruit; public class Apple implements Fruit{ public Apple() { } public String getFruit() { String apple = "apple"; return apple; } }
Orange.java
package com.wzh.fruit.impl; import com.wzh.fruit.Fruit; public class Orange implements Fruit{ public Orange() { } public String getFruit() { String orange = "orange"; return orange; } }
Person.java
package com.wzh.person; import java.lang.reflect.Constructor; import com.wzh.fruit.Fruit; public class Person { private Fruit fruit; public Person(Fruit _fruit) { fruit = _fruit; } public void eat() { System.out.println("I want eat "+fruit.getFruit()); } }
Run.java
package com.wzh.run; import com.wzh.person.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Run { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml"); Person p =(Person)ac.getBean("personOrange"); p.eat(); } }
以上是关于Java依赖注入方式的主要内容,如果未能解决你的问题,请参考以下文章