【问题标题】:Spring: calling method before injectionSpring:注入前调用方法
【发布时间】:2014-12-13 09:23:04
【问题描述】:

我会用一个简单的例子来解释我的问题:

public class A () {
    private B b;

    public A () { /* ... */ }

    public B getB () { /* ... */ }

    @Autowired
    public void setB (B b) { /* ... */ }

    public init (int x, int y, float rx, float ry) { /* ... */ }
}

public class B () {
    private A a;

    public B () { /* ... */ }

    public A getA () { /* ... */ }

    @Autowired
    public void setA (A a) { /* ... */ }

    public init (int x, int y, float rx, float ry) { /* ... */ }
}

所以我需要在注入之前调用 init() 方法,因为在注入后立即从注入的组件中调用方法,以每秒 fps 次循环,当然没有初始化,所以我得到 NullPointerException

我使用 setter 注入并使用 context.getBean("A") 创建对象。

有没有办法在注入前调用方法init()

【问题讨论】:

    标签: java spring dependency-injection javabeans autowired


    【解决方案1】:

    我相信您正在寻找的是@Postconstruct,在 JSR250 中指定,它告诉 Spring 在将依赖项注入您的 bean 后立即运行该方法。您还可以实现InitializingBean 接口。查看this 了解更多详细信息和选项。但是,您的循环依赖会使事情复杂化。 solve this 有几种方法,但归根结底,您最好还是重新设计以消除循环依赖。

    【讨论】:

    • 谢谢,但如您所见,我需要使用参数调用 init(),而在 xml 中我不知道参数.. 只是我创建 A 的方法中的本地字段。
    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    相关资源
    最近更新 更多