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();
}
Abby
  • 3,169
  • 1
  • 21
  • 40

2 Answers2

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(..) {
        ....
    }
}
chrsdbll
  • 176
  • 7
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

Lee Meador
  • 12,829
  • 2
  • 36
  • 42
  • Yes I have annotation-config in xml. Would I be able to use the interface as a parent defining an init-method? – Abby May 16 '13 at 14:12
  • No. The annotation has to go on the bean itself. – Lee Meador May 16 '13 at 14:12
  • I think it would be? e.g . I'll have a go with this and see what happens – Abby May 16 '13 at 14:14
  • 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. – Abby May 16 '13 at 14:36
  • 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. – Lee Meador May 16 '13 at 18:10
  • Yes - I mean abstract java class, not bean - as described in the other answer :) – Abby May 17 '13 at 07:49