在 spring 接線中有一種方法可以在建構式呼叫之前將 application.properties 中定義的屬性連接到用@Value 注釋的相應欄位。
請在下面的代碼中查看我的評論。我希望該欄位prop1(及其值)可供constructor. 是否可以。同樣,我希望該欄位prop1(及其值)可用于該getInstanceProp()方法。是否可以??
package com.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class WirableComponent {
@Value("${prop1}")
String prop1;
String instanceProp = getInstanceProp(); //null - I want prop1 value to be injected before making this method call so i can use it in the method.
public WirableComponent() {
System.err.println("no-args WirableComponent Constructor invoked");
System.err.println("value prop1: " prop1); //null - I want prop1 value to be injected before constructor call so i can use it in constructor.
System.err.println("value instanceProp: " instanceProp); //null
}
public String getInstanceProp() {
System.err.println("value prop1: " prop1);
return null;
}
}
uj5u.com熱心網友回復:
@value 的作業原理類似于 spring 的依賴注入規則,當應用程式背景關系加載并創建 WirableComponent 類的 bean 時,可以通過建構式注入實體化 prop1 值(這可以用于方法呼叫)
例如
@Component
public class WirableComponent {
private final String prop1;
public WirableComponent(@Value("${prop1}") String prop1){
this.prop1 = prop1;
}
}
其次,雖然 prop1 是一個字串文字,但它從 spring 背景關系中獲取值,因此在建構式呼叫發生之前它不能在類中可用,就像在 Java 中一樣:
在位元組碼級別。
- 物件已創建但未初始化。
- 呼叫建構式,將物件作為 this 傳遞
- 當建構式回傳時,物件被完全構造/創建。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/368486.html
