簡體   English   中英

同一個實例如何在 java 中的另一個 class 上以不同的方法工作

[英]how the same Instance work on different method on another class in java

根據提供的參數,在多個方法中使用相同的實例。 我們可以在這里考慮線程安全嗎? 假設我們有 2 class, Class Main & Class demo

Class Demo {
   returnType methodExample(args...) {
      //based on the argument provide it returns
      return something
   }
}

Class Main {
   Demo demo = new Demo();

   returnType method1() {
      value = demo.methodExample(args);
   }
   
   returnType method2() {
      value = demo.methodExample(args);
   }
}

它會共享相同的演示實例嗎? 這兩種方法都是異步工作的。 還請在 Spring Injecting by @AutoWired annotation 中描述案例

對打字錯誤或其他錯誤表示歉意。

是的,它將共享相同的演示實例。 但是計算是在方法 methodExample() 下執行的,它基於您在參數上傳遞的值。 要首先使用@autowire,您必須在演示 Class 上使用@component 注釋。

@Component
Class Demo {
   returnType methodExample(args...) {
      //based on the argument provide it returns
        return something
   }
}
Class Main {
   @Autowired
   Demo demo;

   returnType method1() {
      value = demo.methodExample(args);
   }

   returnType method2() {
      value = demo.methodExample(args);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM