1. @PostConstruct
在项目中看到一种读取配置的方式 其中用到了@PostConstruct这样一个注解,通过这个注解我们可以完成很多初始化工作,包括配置数据的加载。
有以下几点需要注意: 1. 该注解用于修饰一个非静态的void()方法 (这里也能看出他的执行优先级是在静态之后的)2. 被@PostConstruct修饰的方法会在服务器加载Servlet的时候开始执行, 并且只会执行一次。3. 注:PostConstruct会在构造方法执行完再执行,会在init()方法之前执行
执行先后: 静态代码块 > 构造方法 > @PostConstruct > Servlet的init()方法
2. 静态代码块
在了解到这个注解的功能时,第一反应就是和静态代码块很相似,但是两者肯定是有所不同的。于是重新复习一些代码块方面的知识。
静态代码块会在class被加载的时候会执行,并且只会执行一次 (new 两个相同的对象 只会执行一次) 这里顺带提一嘴构造代码块,构造代码块是没有用static修饰的,定义在类中方法外,每次new出这个对象的时候都会执行一次。
摘自: stackoverflow
static blocks are invoked when the class is being initialized, after it is loaded. The dependencies of your component haven't been initialized yet. That is why you get a NullPointerException (Your dependencies are null) .
Move your code to a method annotated with @PostConstruct. This will ensure that your code will run when all the dependencies of your component are initialized
在Spring框架中,静态代码块会在component组件的依赖初始化之前就开始执行其中的内容,因而导致很多的空指针异常,使用@PostConstruct注解可以避免这样异常的发生。
-- Java菜鸟工作之余记录一下,加深一下印象,若有错误望指正