在 @PostConstruct 中分配 bean 值
Assigning bean value in @PostConstruct
在下面的示例中,我需要为 Bean2 分配 Bean1 的一个属性。该属性是 null
(见下文)。此外,“@PostConstruct Bean2”打印在 "After assignment" 之前。
有没有办法确保在 Bean1 中赋值之前创建 Bean2 实例?
@Stateless
public class Bean1 {
@Inject
private Bean2 bean2;
String x;
@PostConstruct
private void init() {
x = "Some Value";
System.out.println("Before assignment");
bean2.setX(x);
System.out.println("After assignment");
}
}
@Stateless
public class Bean2 {
private String x;
public setX(String x) {
this.x = x;
}
@PostConstruct
private void init() {
System.out.println("@PostConstruct Bean2");
System.out.println(x); // <-- x is null
}
}
这是基于您的设置方式的预期行为。 x
应在整个 applicationContext 启动后在 Bean2
中正确设置。
要了解发生了什么,请注意 Bean2
是 Bean1
的依赖项。这意味着 Spring 无法构造 Bean1
直到 after Bean2
被创建。因此它首先创建 Bean2
,然后您会看到 init()
块中的 x
为空,因为 Bean1
尚未构建,无法设置其值。
后面会构造Bean1
,调用它的init()
方法,正确设置Bean2
中x
的值。但这发生在 Bean2
的 @PostConstruct
已经完成很久之后。
在下面的示例中,我需要为 Bean2 分配 Bean1 的一个属性。该属性是 null
(见下文)。此外,“@PostConstruct Bean2”打印在 "After assignment" 之前。
有没有办法确保在 Bean1 中赋值之前创建 Bean2 实例?
@Stateless
public class Bean1 {
@Inject
private Bean2 bean2;
String x;
@PostConstruct
private void init() {
x = "Some Value";
System.out.println("Before assignment");
bean2.setX(x);
System.out.println("After assignment");
}
}
@Stateless
public class Bean2 {
private String x;
public setX(String x) {
this.x = x;
}
@PostConstruct
private void init() {
System.out.println("@PostConstruct Bean2");
System.out.println(x); // <-- x is null
}
}
这是基于您的设置方式的预期行为。 x
应在整个 applicationContext 启动后在 Bean2
中正确设置。
要了解发生了什么,请注意 Bean2
是 Bean1
的依赖项。这意味着 Spring 无法构造 Bean1
直到 after Bean2
被创建。因此它首先创建 Bean2
,然后您会看到 init()
块中的 x
为空,因为 Bean1
尚未构建,无法设置其值。
后面会构造Bean1
,调用它的init()
方法,正确设置Bean2
中x
的值。但这发生在 Bean2
的 @PostConstruct
已经完成很久之后。