[英]Spring inject property values from a bean into another bean
在我的 Spring Boot 項目中有 2 個 java bean。 第一個 bean 從屬性文件(spring 注入)中獲取值,第二個 bean 從不同的源獲取值。
spring 初始化后,我想將第二個 bean 中的屬性值合並到第一個 bean 中。 請知道 spring 是否提供任何類來動態注入值。
first bean gets the values from property file:
----------------------------------------------
@value("username")
private String username
@Value("server")
private String servername
@Value("inject from second bean")
private String location
@Value("inject from second bean")
private boolean enabled
second bean gets the values from different source
-----------------------------------------------
private String location
private boolean enabled
嘗試使用表達式語言:
@Value(#{anotherBean.location})
private String location
@Value(#{anotherBean.enabled})
private boolean enabled
更新
或者,您可以在 post 構造中分配它:
@Autowired
private AnotherBean anotherBean;
@PostConstruct
public void init(){
location = anotherBean.getLocation();
enabled = anotherBean.isEnabled();
}
更新 2
我想到的最后一件可以開箱即用的事情是將第一個 bean 的范圍更改為原型而不是單例:
@Scope("prototype")
現在每次使用這個 bean 時(例如在 spring 上下文中使用 getBean)都會創建一個新實例……並且每次都會注入來自 anotherBean 的新數據。
但這是特定的,因此您必須考慮這種情況是否適合您的應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.