@PostConstruct与@PreDestroy笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunshine_YG/article/details/83089027

自测后执行顺序与网上有些不同。

1、构造函数

2、@PostConstruct

3、init

4、@PreDestroy

5、destroy

具体测试类:

package com.sunshine.shine.Test.PostConstructTest;

import org.springframework.stereotype.Component;

@Component
public class Eraser {
    public String name="oneEraser";
    public String desName="oh my god";
}
package com.sunshine.shine.Test.PostConstructTest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.LocalDateTime;

@Component
public class Pencil {

    @Autowired
    private Eraser eraser;


    Pencil(){
        System.out.println("=====构造=====");
    }

    @PostConstruct
    public void initPencil(){
        System.out.println("===== my eraser ====="+eraser.name);
    }
    public void init(){
        System.out.println("===== init =====");
    }
    @PreDestroy
    public void desPencil(){
        System.out.println("===== destory ====="+eraser.desName);
    }
    public void destroy(){
        System.out.println("==== destroy =====");
    }
}
package com.sunshine.shine.Test.PostConstructTest;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class PostConstruct {

//    @Autowired
//    private

    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Pencil pencil(){
        return new Pencil();
    }
}

执行结果:

猜你喜欢

转载自blog.csdn.net/sunshine_YG/article/details/83089027