@PostConstruct 注解的使用

@PostConstruct 是 javax.annotation 包下注解之一,源码注解如下:

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependencyinjection. The method annotated with PostConstruct MUST be invoked even if the class does not request any resources to be injected. Only one method can be annotated with this annotation…

概括起来,其作用就是完成依赖注入后,在对象的非静态的 void 方法内执行特定任务,以确保在对象使用之前可以将任务执行效果使用起来。

描述起来可能比较抽象,用一个Spring Boot项目的简单例子说明一下。

案例:

在开发初期,使用Windows系统电脑进行开发,偶尔在服务器上进行测试,在存储文件时,会涉及路径问题,由于Win和Linux路径不一致,需要配置不同的测试路径。如:图片的上传测试,在.yml 测试文件的配置如下:

...
picture:
  linuxDir: /tmp/img_test
  winDir: C:\Users\dash\img_test

在运行图片上传服务时需要决定使用哪个路径。为了可以在系统运行后,一次进行判定系统类型,选择合适的路径,可以用如下代码进行实现:

public class FileTransferServiceImpl implements FileTransferService {

    @Value("${picture.linuDir}")
    private String linuxImgDir;

    @Value("${picture.winDir}")
    private String winImgDir;
    
    private String imgDir;

    @PostConstruct
    public void init() {
        imgDir = linuxImgDir;
        if (!OsUtils.isLinxu()) {
            imgDir = winImgDir;
        }
    }
    
    ...
}

@Value 将Spring Boot 的配置文件内相关信息注入进来,而后标注了@PostConstructinit() 方法开始执行,进行一次系统类型的判断,完成imgDir的赋值,使得FileTransferServiceImpl被调用之前,imgDir准备完毕,不再为null,可以自由调用,规避了加载顺序可能带来的问题。

发布了19 篇原创文章 · 获赞 83 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/weixin_43838898/article/details/102721194
今日推荐