Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use @PostConstruct on an interface method?

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();
}
like image 635
Abby Avatar asked May 16 '13 14:05

Abby


People also ask

What is the @PostConstruct annotation used for?

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.

Is @PostConstruct deprecated?

In jdk9 @PostConstruct and @PreDestroy are in java. xml. ws. annotation which is deprecated and scheduled for removal.

In what order do the @PostConstruct annotated method the Init method?

Correct? Despite you use asynchronized method, these postConstruct methods wil be executed sequentially. Then, ServiceA#init() will be finished when ServiceB#init() will begin.

What can I use instead of PostConstruct?

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.


1 Answers

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(..) {
        ....
    }
}
like image 154
chrsdbll Avatar answered Oct 13 '22 00:10

chrsdbll