@PostConstruct(注解的方法)

232 阅读1分钟

@PostConstruct注解的方法会将在依赖注入完成之后被自动调用。该注解在整个Bean初始化中执行的顺序:

@Constructor(构造方法)->@Autowired(依赖注入)->@PostConstruct(注解的方法)

使用场景:在静态方法中调用依赖注入的Bean中的方法

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
import javax.annotation.PostConstruct;
 
@Component
public class FTPUtils {
    /**
     * FTP的连接池
     */
    @Autowired
    public static FTPClientPool ftpClientPool;
    /**
     * FTPClient对象
     */
    public static FTPClient ftpClient;

    /**
     * 初始化设置
     *
     * @return
     */
    @PostConstruct
    public boolean init() {
        FTPClientFactory factory = new FTPClientFactory();
        try {
            ftpClientPool = new FTPClientPool(factory);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取连接对象
     *
     * @return
     * @throws Exception
     */
    public static FTPClient getFTPClient() throws Exception {        //初始化的时候从队列中取出一个连接
        if (ftpClient == null) {
            synchronized (ftpClientPool) {
                ftpClient = ftpClientPool.borrowObject();
            }
        }
        return ftpClient;
    }