I have used afterPropertiesSet()
to initialize class properties in Spring beans. Now I see that this task can be accomplished by Java's built in static and non-static initializers. What can I do with afterPropertiesSet()
that I cannot with the initializer blocks?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Given the following class
The static initializer block is only executed when the class is loaded by the class loader. There is no instance of that class at that moment and you will only be able to access class level (
static
) variables at that point and not instance variables.The non-static initializer block is when the object is constructed but before any properties are injected. The non-static initializer block is actually copied to the constructor.
See also Static Initialization Blocks and http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
The
afterPropertiesSet
or@PostConstruct
annotated method is called after an instance of class is created and all the properties have been set. For instance if you would like to preload some data that can be done in this method as all the dependencies have been set.If you only have mandatory dependencies you might be better of using constructor injection and instead of using
InitializingBean
or@PostConstruct
put the initializing logic in the constructor. This will only work if all the dependencies are injected through the constructor, if you have optional dependencies set by set methods then you have no choice but to use@PostConstruct
orInitializingBean
.