本文主要是介绍@PostConstruct与@PreDestroy笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
自测后执行顺序与网上有些不同。
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 {@Autowiredprivate Eraser eraser;Pencil(){System.out.println("=====构造=====");}@PostConstructpublic void initPencil(){System.out.println("===== my eraser ====="+eraser.name);}public void init(){System.out.println("===== init =====");}@PreDestroypublic 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();}
}
执行结果:
这篇关于@PostConstruct与@PreDestroy笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!