下面展示spring的注入方式,主要是:
兩個接口:
Axe.java:
package com.jim.service;
public interface Axe {
public String chop();
}
接口二:Person.java:
package com.jim.service;
public interface Person {
public void useAxe();
}
接口實現類:
package com.jim.service.impl;
import com.jim.service.Axe;
public class StoneAxe implements Axe {
public String chop() {
return "石頭斧頭";
}
}
1.設值注入:
在Person實現類Man的實現上:
package com.jim.service.impl;
import com.jim.service.Axe;
import com.jim.service.Person;
public class Man implements Person {
private Axe axe;
public void setAxe(Axe axe){
this.axe = axe;
}
public void useAxe() {
System.out.println(axe.chop());
}
}
2.構造注入:
package com.jim.service.impl;
import com.jim.service.Axe;
import com.jim.service.Person;
public class Man implements Person {
private Axe axe;
public void Man(){}
public Man(Axe axe) {
super();
this.axe = axe;
}
public void useAxe() {
System.out.println(axe.chop());
}
}
同時spring的配置文件bean.xml的區別是:
<?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="man" class="com.jim.service.impl.Man">
<property name="axe" ref="steelAxe"/>
</bean>
-->
<!--構造注入的方式-->
<bean name="man" class="com.jim.service.impl.Man">
<constructor-arg ref="steelAxe"/>
</bean>
<bean id="stoneAxe" class="com.jim.service.impl.StoneAxe" />
<bean id="steelAxe" class="com.jim.service.impl.SteelAxe"/>
</beans>
測試類:
package com.jim.service.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jim.service.Person;
public class BeanTest {
@Test
public void testPerson(){
ApplicationContext actx = new ClassPathXmlApplicationContext("bean.xml");
Person person = actx.getBean("man", Person.class);
person.useAxe();
}
}