我正在构建一个 Spring Boot 应用程序。我将有 2 个服务类 A 和 B,B.getStringNextValue() 返回一个在 A.getStringValue() 中调用的值,但 A.getStringValue() 类中 b.getStringNextValue() 的值没有/null。
我已经尝试过下面的代码,并在 StackOverflow 中搜索了一些问题,但没有答案解决了这个问题。
@Service
public 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,
@Service
public class B {
public StringBuilder getStringNextValue() {
StringBuilder str = new StringBuilder();
str.append(" World");
System.out.println(str.toString()); //Here i get ' World'
return str;
}
}
我不知道为什么会得到这种类型的输出。谁能描述一下并建议我一些解决方案?谢谢。
最佳答案
我测试了你的代码,没有获得与你相同的打印结果。你如何测试你的代码?
这是我的单元测试,在 'zp:'
之后的代码中添加了注释。请注意,b.getStringNextValue()
每次都会发送“World”。我还在最后一个 System.out.println(str) 上获得了“Hello World”。希望对您有帮助。
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
关于java - 在 Spring Boot 中,为什么我没有将一个服务类的返回值返回到另一个服务类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248470/