探究Spring中 構造方法、@PostConstruct、@Autowired、@Value 的加載順序
@Service
public class TestService {
public String get () {
return "hello world";
}
}
@RestController
public class TestController {
public TestController () {
System.err.println("---------------------------------");
System.err.println("這是構造方法");
System.err.println("testService = " + testService);
System.err.println("testUrl = " + testUrl);
System.err.println("---------------------------------");
}
private String testUrl;
@Value("${emop.config.url}")
public void setTestUrl (String testUrl) {
this.testUrl = testUrl;
System.err.println("---------------------------------");
System.err.println("這是@Value");
System.err.println("testService = " + testService);
System.err.println("testUrl = " + testUrl);
System.err.println("---------------------------------");
}
TestService testService;
@Autowired
public void setTestService (TestService testService) {
this.testService = testService;
System.err.println("---------------------------------");
System.err.println("這是@Autowired");
System.err.println("testService = " + testService);
System.err.println("testUrl = " + testUrl);
System.err.println("---------------------------------");
}
@PostConstruct
public void testPostConstructor () {
System.err.println("---------------------------------");
System.err.println("這是@PostConstruct方法");
System.err.println("testService = " + testService);
System.err.println("testUrl = " + testUrl);
System.err.println("---------------------------------");
}
@GetMapping("/get")
public String get () {
return testService.get();
}
}
從項目啓動的2次輸出結果可以看出,依次打印了:構造方法 》@Autowired/@value 》@PostConstruct,@Autowired和@value的加載應該不分先後