所需文件為:
1.接口:
package com.get;
public interface ProductInterface {
public void add();
}
2.implement類:
package com.get;
public class Product implements ProductInterface {
public void add(){
System.out.println("add");
}
}
3.含有setter方法的Helper類:
需要注意的地方:xml文件的bean:
<!--
在Helper類進行了實例化,setter注入,setter注入相當於new 一個對象,在哪new?在Helper(即在setter方法的類中)類的bean中,一般的對類進行的操作,通過new一個對象,而在spring中,通過setter注入方法與其bean的合作,相當於一個new的操作,原來為2或3步操作即可new一個對象,現在需要再加一步了,即:interface,implement,setter方法,ApplicationContext的getBean
-->
<bean id="product" class="com.get.Product"></bean>
<bean name="productimp" class="com.get.Helper">
<property name="product" ref="product" />
</bean>
</beans>
package com.get;
import com.get.ProductInterface;
public class Helper {
ProductInterface product; // ? 全部 感覺 相當於 new 一個對象啦
public void setProduct(ProductInterface productInterface){
this.product=productInterface;
}
public void addadd(){
product.add();
}
}
4.ApplicationContext:
package com.get;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.get.Product;
public class Productproduct {
public static void main(String[] args){
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("Example.xml");
Helper productInterface=(Helper)applicationContext.getBean("productimp");
productInterface.addadd();
}
}