Spring中构造方法、@PostConstruct、@Autowired、@Value的加载顺序

探究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();
    }
}

img

img

从项目启动的2次输出结果可以看出,依次打印了:

构造方法 --> @Autowired/@value --> @PostConstruct,@Autowired和@value的加载应该不分先后

猜你喜欢

转载自blog.csdn.net/qq_43842093/article/details/130173665
今日推荐