I'm building a Spring Boot application. I will have 2 service classes A and B, B.getStringNextValue() return a value which called in A.getStringValue() but value of b.getStringNextValue() in A.getStringValue() class have nothin/null.
I already tried below code and also search some questions in StackOverflow but no ane Answer was solved this.
@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();
}
}
And 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;
}
}
I don`t know why I get this type of output. can anyone describe it and suggest me some solution? Thanks.
I tested you code and did not obtain the same print results as you. How do you test you code? Here is my unit test with comments in code after 'zp:'
. Note that b.getStringNextValue()
sends ' World' everytime. And also i obtain 'Hello World' on the last System.out.println(str)
. Hope it will help you.
Class 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();
}
}
Class 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;
}
}
My test here :
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();
}
}
The output is :
World
World
World
Hello World
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.