Spring在调用时从其他方法获取值

fykwrbwg  于 2022-10-04  发布在  Spring
关注(0)|答案(1)|浏览(162)

实现:在Service1中,将在方法transerValue中的service2中返回值,但当稍后调用CalledLaterMethod时,但当我尝试访问CalledLaterMethod中的transerValue时,它为空。有没有可能将值存储在transerValue中,并等待CalledLaterMethod被调用并获得该值?对于任何解决方案,请让我知道

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Class1{

  private String param1;
  private String param2;

}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Class2{

  private String param4;
  private String param5;

}
@Slf4j
@Service
public class Service1{

// with method for validationString

  public Class1 validationString(String val1, String val2){

        String present = "PRESENT";
        String empty = "EMPTY";

        String param1Transfer = "";
        String param2Transfer = "";

         if(val1.isEmpty()) param1Transfer = empty;
        else param1Transfer = present;
        if(val2.isEmpty()) param2Transfer = empty;
        else param2Transfer = present;
         Class1 class1 = Class1.builder()
                .param1(param1Transfer)
                .param2(param2Transfer)
                .build();
        return Service2.transerValue(class1);

  }

}
@Slf4j
@Service
public class Service2{

   public static Class1 transerValue(Class1 class1){
   //log will work
   log.info("Well this data show ={}",class1 );
   return class1;
   }

   //this method CalledLaterMethod will be called later and i must get the value being transfer in transerValue
   // and must not change the parameter of CalledLaterMethod
   public static Class2 CalledLaterMethod(OtherClass1 other1,OtherClass other2 ){

   // i tried
   //this is null
   Class1 class1 = new Class1();
   Class1 classClone = transerValue(class1)
   log.info(classClone);

   //trying to do

  Class2 class2 = Class2.builder.
   .param4(classClone.getParam1)
   .param5(classClone.getParam2)
   build();

   return class2;

   }

}
aor9mmx1

aor9mmx11#

您将始终得到NULL,因为您没有在CalledLaterMethod中的Class1中设置任何值,在那个类中,您只示例化对象Class1而不设置该对象中的值,除非您在CalledLaterMethod中传递了值Class1 from参数。我假设OtherClass1是要传递的Class1对象,如果不想更改CalledLaterMethod中的参数,可以这样做

public class Service2{

       public static Class1 transerValue(Class1 class1){
       //log will work
       log.info("Well this data show ={}",class1 );
       return class1;
       }

       //this method CalledLaterMethod will be called later and i must get the value being transfer in transerValue
       // and must not change the parameter of CalledLaterMethod
       public static Class2 CalledLaterMethod(OtherClass1 other1,OtherClass other2 ){

       // assign object from parameter to a new object called class1
       Class1 class1 = other1;
       Class1 classClone = transerValue(class1)
       log.info(classClone);

       //trying to do

      Class2 class2 = Class2.builder.
       .param4(classClone.getParam1)
       .param5(classClone.getParam2)
       build();

       return class2;

       }

    }

相关问题