亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 spring boot 中,為什么我沒有將一個服務類的返回值返回給另一個服務類

在 spring boot 中,為什么我沒有將一個服務類的返回值返回給另一個服務類

HUWWW 2023-04-26 17:05:31
我正在構建一個 Spring Boot 應用程序。我將有 2 個服務類 A 和 B,B.getStringNextValue() 返回一個在 A.getStringValue() 中調用的值,但 A.getStringValue() 類中 b.getStringNextValue() 的值沒有任何內容/為空。我已經嘗試了下面的代碼,還在 StackOverflow 中搜索了一些問題,但沒有一個答案解決了這個問題。@Servicepublic class A{    @Autowired    private B b;    public String getStringValue(){        StringBuilder str = new StringBuilder("Hello ");        str.append(b.getStringNextValue());        System.out.println(b.getStringNextValue()); //here nothing as output but expectation is ' World'        System.out.println(str); //here i only get 'Hello ' But expectation is 'Hello World'        return str.toString();    }}而B.java,@Servicepublic class B {    public StringBuilder getStringNextValue() {        StringBuilder str = new StringBuilder();        str.append(" World");        System.out.println(str.toString()); //Here i get ' World'        return str;    }}我不知道為什么我會得到這種類型的輸出。任何人都可以描述它并建議我一些解決方案嗎?謝謝。
查看完整描述

1 回答

?
瀟湘沐

TA貢獻1816條經驗 獲得超6個贊

我測試了你的代碼,并沒有獲得與你相同的打印結果。你如何測試你的代碼?這是我的單元測試,在之后的代碼中有注釋'zp:'。請注意,b.getStringNextValue()每次都發送“World”。而且我在最后獲得了“Hello World” System.out.println(str)。希望它能幫助你。


A類:


package test;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;


@Service

public class A {


    @Autowired

    private B b;


    public String getStringValue() {

        StringBuilder str = new StringBuilder("Hello ");

        str.append(b.getStringNextValue()); // zp: This line prints ' World' AND make str = 'Hello World'

        System.out.println(b.getStringNextValue()); // here nothing as output but expectation is ' World' -> zp: Prints ' World'

        System.out.println(str); // here i only get 'Hello ' But expectation is 'Hello World' -> zp: 'Hello World' is printed

        return str.toString();

    }

}

B類:


package test;


import org.springframework.stereotype.Service;


@Service

public class B {


    public StringBuilder getStringNextValue() {

        StringBuilder str = new StringBuilder();

        str.append(" World");

        System.out.println(str.toString()); // Here i get ' World' -> zp: Yes, 2 times

        return str;

    }

}

我在這里的測試:


import test.A;

import test.B;


@RunWith(SpringRunner.class)

public class MyTest {


    @Configuration

    @ComponentScan("test")

    static class Config {}


    @Autowired

    private A a;


    @Autowired

    private B b;


    @Test

    public void test() {

        a.getStringValue();

    }

}

輸出是:


 World

 World

 World

Hello  World


查看完整回答
反對 回復 2023-04-26
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號