I have a number of beans implementing an interface and I'd like them all to have the same @PostConstruct. I've added the @PostConstruct
annotation to my interface method, then added to my bean definitions:
<bean class="com.MyInterface" abstract="true" />
But this doesn't seem to be working. Where am I going wrong if this is even possible?
edit: I've added the annotation to the interface like this:
package com;
import javax.annotation.PostConstruct;
public interface MyInterface {
@PostConstruct
void initSettings();
}
Annotation Type PostConstruct 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 dependency injection.
In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.
Correct? Despite you use asynchronized method, these postConstruct methods wil be executed sequentially. Then, ServiceA#init() will be finished when ServiceB#init() will begin.
We can replace @PostConstruct with BeanFactoryPostProcessor and PriorityOrdered interface. The first one defines an action that ought to be executed after the object's instantiation. The second interface tells the Spring the order of the component's initialization.
The @PostConstruct has to be on the actual bean itself, not the Interface class. If you want to enforce that all classes implement the @PostConstruct method, create an abstract class and make the @PostConstruct method abstract as well.
public abstract class AbstractImplementation {
@PostConstruct
public abstract init(..);
}
public class ImplementingBean extends AbstractImplementation {
public init(..) {
....
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With