簡體   English   中英

在Spring中獲取具有特定參數的bean到構造函數

[英]Get bean with specific Arguments to constructor in Spring

假設我有那堂課

public Student{
 private String name;
 private Address address;

 public Student(String fName, Address address){
  name = fname;
  this.address = address;
}

我在Spring配置中將此類定義為

 <bean name="studentInstance" class="StackOverFlow.Student"/>

現在我想將getBean與參數一起使用,該參數將傳遞給構造函數。 等於Student s = new Student(name,address)我知道Spring提供了一個方法getBean(class_name,parms ....),但是我不知道如何配置Spring.xml配置文件。 我想避免使用Setter和getter來填充新的bean。

我發現了很多示例,說明如何在xml中定義</constructor-arg> ,但是每次都使用默認值。 在這里,我讓用戶為每個對象輸入不同的值。 我想使用ApplicationContext context = new ClassPathXmlApplicationContext(Spring.xml file path); Student s= (Student)context.getBean("studentInstance",name,address); ApplicationContext context = new ClassPathXmlApplicationContext(Spring.xml file path); Student s= (Student)context.getBean("studentInstance",name,address);

我只需要有關配置文件的幫助

提前致謝!!

我已經檢查了那些鏈接: Link1 Link2 Link3 Link4

~~~~~編輯~~~~~~~

解決了! 這里不需要構造函數注入,我只是將原型作用域添加到了bean中,如下所示。

<bean name="carInstance" class="MainApp.bl.GasStation.Car" scope="prototype"/>

首先,顯然必須將此類bean聲明為原型。

原型將單個bean定義的作用域限定為具有任意數量的對象實例。 如果將范圍設置為原型,則每次對特定bean發出請求時,Spring IoC容器都會創建該對象的新bean實例。

Object getBean(String name, Object... args)throws BeansException

返回一個實例,該實例可以是指定bean的共享或獨立的。 允許指定顯式構造函數自變量/工廠方法自變量,覆蓋Bean定義中指定的默認自變量(如果有)。

請參考以下問題進行配置:

Spring <constructor-arg>元素必須指定ref或value

注意,您必須將原語包裝到其Wrapper對象中,以避免在創建對象時具有預定義的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM