簡體   English   中英

如何在運行時使用動態參數(不是原型bean)初始化Spring bean?

[英]How to initialize Spring bean with dynamic arguments at run-time which is not prototype bean?

我正在嘗試使用請求范圍初始化Spring bean,並從不受Spring管理的另一個對象(屬性)進行延遲初始化。 這是bean的定義:

@Component
@Scope(value = "request")
@Lazy
public class LazyClass {

 protected String name;

}

如何在運行時初始化'name'屬性?

它可能不是最佳解決方案,但是您可以將name的值設置為System屬性,並在類中所需的位置獲取它。

在非spring類的某個地方設置值:

// myProperty is the name of the property
// name is the value you want to store
System.setProperty("myProperty",name);

進入課堂:

// Caution: the name of the property must be the same as it was when it was set
String name = System.getProperty("myProperty);

可以在bean類的構造函數中調用@Lazy因為它被標記為@Lazy

編輯:

另一種方法是為字段name創建一個setter,並在需要時設置其值。

暫無
暫無

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

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