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
添加回答
举报