我可以在接口方法上使用@PostConstruct吗?

Abb*_*bby 15 java spring interface postconstruct

我有许多实现接口的bean,我希望它们都具有相同的@PostConstruct.我已经将@PostConstruct注释添加到我的接口方法中,然后添加到我的bean定义中:

<bean class="com.MyInterface" abstract="true" />
Run Code Online (Sandbox Code Playgroud)

但这似乎并没有起作用.如果可能的话,我哪里出错了?

编辑:我已经将注释添加到界面中,如下所示:

package com;
import javax.annotation.PostConstruct;
public interface MyInterface {
    @PostConstruct
    void initSettings();
}
Run Code Online (Sandbox Code Playgroud)

小智 13

@PostConstruct必须位于实际的bean本身,而不是Interface类.如果要强制所有类实现@PostConstruct方法,请创建一个抽象类,并使@PostConstruct方法也是抽象的.

public abstract class AbstractImplementation {

    @PostConstruct
    public abstract init(..);
}

public class ImplementingBean extends AbstractImplementation {
    public init(..) {
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)