原创

【Spring那些事】@PostConstruct注解如何使用

温馨提示:
本文最后更新于 2023年03月06日,已超过 415 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

@PostConstruct注解的方法在构造方法执行后将会被调用

@Autowired注入注解是在构造方法执行完成后才能完成属性的注入

所以当在构造方法内进行使用注入的属性时将无法获取

示例

UserServiceImpl.java

@Service
public class UserServiceImpl {
    @Autowired
    private DeptServiceImpl deptService;

    public UserServiceImpl() {
        System.out.println("Constructor::"+deptService);
    }

    @PostConstruct
    public void init() {
        System.out.println("@PostConstruct::"+deptService);
    }
}

DeptServiceImpl.java

@Service
public class DeptServiceImpl {
}

UserServiceImpl中通过@Autowired注入DeptServiceImpl

当在UserServiceImpl的构造方法中引用deptService时,此时deptService为null

运行结果

可以看到在,@Autowired注解需要在构造方法执行完成后才能完成注入
init方法被@PostConstruct修饰,在构造方法执行后进行调用init方法
file

正文到此结束
本文目录