2019-08-29 Spring初始化执行Method的方式有两种

Spring初始化执行Method的方式有两种

1、@PostConstruct

import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
public class College {
    public College() {
        System.out.println("college construct");
    }
    @PostConstruct
    public void init() {
        System.out.println("college init method by @PostConstruct");
    }
}

打印

college construct
college init method by @PostConstruct

2、实现InitializingBean

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class University implements InitializingBean {
    public University() {
        System.out.println("University construct");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("University init method by InitializingBean");
    }
}

打印

college construct
college init method by InitializingBean

3、谁先执行

那我们就比较一下 是先执行@PostConstruct还是先执行 initializingBean的afterPropertiesSet

package com.sdnware.sfc.test;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class College implements InitializingBean {

    public College() {
        System.out.println("college construct");
    }

    @PostConstruct
    public void init() {
        System.out.println("college init method by @PostConstruct");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("college init method by InitializingBean");
    }
}

打印

college construct
college init method by @PostConstruct
college init method by InitializingBean

说明会先执行PostConstruct再执行afterPropertiesSet

你可能感兴趣的:(2019-08-29 Spring初始化执行Method的方式有两种)