spring的setter注入初使用+個人理解


所需文件為:

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();

}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM