gpt4 book ai didi

java - 如何用动态值实例化构造函数并 Autowiring 它?

转载 作者:行者123 更新时间:2023-12-01 18:00:31 24 4
gpt4 key购买 nike

我在这里实例化了一个参数化构造函数,称为具有动态值的请求操作。如何将其@Autowire到Requestclass?随后,在Request类中,我创建了一个新的RatingResponse如何@Autowire这个?

类初始化器

public class Intializer
{
NewClass newclass = new NewClass();
String testName = Number + "_" + "Test"; -->getting the String number dynamically
Test test = new Test(testName); -> this is a different class

Operation operation = new RequestOperation(test, newclass ,
sxxx, yyy, zzz); - argumented constructor
opertaion.perform();
}

请求类

public class RequestOperation implements Operation { 

// the constructor
public RequestOperation(Test test, Sheet reportSheet, XElement element, TestDataManager testDataManager, Report report)
{
this.test = test;
this.newclass = newclass ;
this.sxxx= sxxx;
this.yyy= yyy;
this.zzz= zzz;
}
@Override
public boolean perform(String CompanyName, String Province) {
Response response = new RatingResponse(this.test, this.reportSheet,
callService(this.buildRequest(CompanyName, Province)), this, this.report);-> create a new paramterizedconstructor
}

private String buildRequest(String CompanyName, String Province) {
return pm.getAppProperties().getProperty(constructedValue); }
}

**响应类**

    public class RatingResponse implements Response {
public RatingResponse(Test test, Sheet reportSheet, Object obj, RequestOperation requestOperation, Report report) {
this.test = test;
if (obj instanceof Document) {
this.document = (Document) obj;
}
this.operation = requestOperation;
this.reportSheet = reportSheet;
this.report = report;
}

** 界面 **

@Component
public interface Operation {
public boolean perform(String Name, String Province);
}

@Component
public interface Response {

void construct();

}

最佳答案

在 Spring Boot 中,您只能 Autowiring 标有 @Bean 的类型或标有 @Component 或其派生类(例如 @Service、@Controller)的类

这些注释的特殊之处在于内存中仅保留该类的单个实例。

因此,如果您的要求需要为每组新动态值创建新类,那么 Autowiring 它们并不是正确的方法。

但是,如果您的类可以拥有的动态值数量有限,您可以像这样为每个值创建 bean

@Configuration
class MyBeans{

@Bean
public RatingResponse ratingResponse(){

Response response = new RatingResponse(this.test, this.reportSheet,
callService(this.buildRequest(CompanyName, Province)), this, this.report);
return response
}

}

然后在你需要使用的类中,就可以这样做

@Autowired 
RatingResponse ratingResponse

关于java - 如何用动态值实例化构造函数并 Autowiring 它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60642293/

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