如何使用动态值实例化构造函数并自动装配它?

问题描述 投票:0回答:1

我已经实例化了一个参数化的构造函数,在这里称为带有动态值的请求操作。如何@Autowire这到Requestclass?随后,在Request类中,我创建了一个new 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();
}

RequestClass

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();

}
java spring-boot constructor autowired spring-annotations
1个回答
0
投票

在春季启动中,您只能自动装配标有@Bean的类型或标有@Component或其派生类(如@ Service,@ Controller的类)>

这些注释的特长是该类的单个实例仅保留在内存中。

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

但是,如果您的类可能具有的动态值数量有限,则可以像这样为它们中的每一个创建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
© www.soinside.com 2019 - 2024. All rights reserved.