Can I use @PostConstruct on an interface method?
Asked Answered
O

2

15

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();
}
Orfinger answered 16/5, 2013 at 14:2 Comment(2)
Show us more, please. What do you mean "added the annotation"?Pedal
I've added a little more of a code snippet. Does that help? Thank youOrfinger
P
15

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(..) {
        ....
    }
}
Playbook answered 16/5, 2013 at 14:20 Comment(0)
P
1

@PostConstruct has to go on the bean java class itself. I don't know what it will do on an interface.

Do you have this in your XML?

<context:annotation-config />

Here is some example code: @PostConstruct example

Pedal answered 16/5, 2013 at 14:9 Comment(6)
Yes I have annotation-config in xml. Would I be able to use the interface as a parent defining an init-method?Orfinger
No. The annotation has to go on the bean itself.Pedal
I think it would be? e.g <bean abstract="true" class="com.MyInterface" id="myParent" init-method="initSettings"/><bean class="com.ImplementingBean" parent="myParent" />. I'll have a go with this and see what happensOrfinger
Yes, seems to work. I think I will opt for using the abstract class on this occassion though as there are many beans which would need setting to have the parent.Orfinger
It might be more descriptive to say you are using an abstract Spring bean since "class" could be taken to refer to the Java class which could be abstract as well.Pedal
Yes - I mean abstract java class, not bean - as described in the other answer :)Orfinger

© 2022 - 2024 — McMap. All rights reserved.