美文网首页
2019-08-29 Spring初始化执行Method的方式有

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

作者: 杨浩0712 | 来源:发表于2019-08-29 14:15 被阅读0次

    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的方式有

          本文链接:https://www.haomeiwen.com/subject/umjiectx.html