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


我有很多实现接口的bean,我希望它们都具有相同的@PostConstruct。我添加了 @PostConstruct 我的接口方法的注释,然后添加到我的bean定义:

<bean class="com.MyInterface" abstract="true" />

但这似乎并没有奏效。如果可能的话,我哪里出错了?

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

package com;
import javax.annotation.PostConstruct;
public interface MyInterface {
    @PostConstruct
    void initSettings();
}

6207
2018-05-16 14:02


起源

请告诉我们更多。你是什​​么意思“添加了注释”? - Lee Meador
我添加了一些代码片段。这有帮助吗?谢谢 - Abby


答案:


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

public abstract class AbstractImplementation {

    @PostConstruct
    public abstract init(..);
}

public class ImplementingBean extends AbstractImplementation {
    public init(..) {
        ....
    }
}

10
2018-05-16 14:20





@PostConstruct 必须继续bean java类 本身。我不知道它会在界面上做什么。

你的XML中有这个吗?

<context:annotation-config />

这是一些示例代码: @PostConstruct示例


1
2018-05-16 14:09



是的我在xml中有annotation-config。我是否可以将该接口用作定义init方法的父级? - Abby
不。注释必须在bean本身上进行。 - Lee Meador
我想会是吗?例如<bean abstract =“true”class =“com.MyInterface”id =“myParent”init-method =“initSettings”/> <bean class =“com.ImplementingBean”parent =“myParent”/>。我会对此有所了解,看看会发生什么 - Abby
如果有效,请告诉我们。它可能会这样做。 - Lee Meador
是的,似乎有效。我想我会选择在这个场合使用抽象类,因为有很多bean需要设置为拥有父级。 - Abby