【问题标题】:How to instantiate constructor with dynamic value and Autowire it?如何用动态值实例化构造函数并自动装配它?
【发布时间】:2020-03-11 18:18:23
【问题描述】:

我在这里实例化了一个参数化构造函数,称为具有动态值的请求操作。如何@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();
}

请求类

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】:

    在 Spring Boot 中,您可以仅自动装配标有 @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
    

    【讨论】:

    • MyBeans中如何获取test、reportsheet等的值
    猜你喜欢
    • 2017-03-09
    • 2022-11-29
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多