gpt4 book ai didi

java - 如何使用带有构造函数参数的 Spring Prototype Beans?

转载 作者:行者123 更新时间:2023-12-05 01:16:06 24 4
gpt4 key购买 nike

<分区>

我确实使用 Spring 和 Lombok。
没有原型(prototype) bean,我们必须传递目标类所需的依赖项。
我们如何将 bean 标记为原型(prototype)并正确处理依赖 bean 和构造函数参数?

选项 1 - 无原型(prototype) bean

@Component @RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Consumer {
private final SomeDependency iDontNeed; // Consumer class doesn't need
private final SomeDependency2 iDontNeed2;

public void method() {
new Processor("some random per request data", iDontNeed, iDontNeed2);
}
....
@Value @RequiredArgsConstructor
public class Processor {
private final String perRequestInputData;
private final SomeDependency iReallyNeed;
private final SomeDependency2 iReallyNeed2;
}

选项 2 - 原型(prototype) bean

@Component @RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Consumer {
private final Provider<Processor> processorProvider;

public void method() {
Processor p = processorProvider.get();
p.initializeWith("some random per request data");
}
....
@Component @Scope("prototype")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class Processor {
private final SomeDependency iReallyNeed;
private final SomeDependency2 iReallyNeed2;

private String perRequestInputData; //wish I was final
private boolean initialized; //wish I was not needed

public void initializeWith(String perRequestInputData) {
Preconditions.checkState(!initialized);
this.perRequestInputData = perRequestInputData
initialized = true;
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com