Java Springbean已创建,但自动连接时为空

Java Springbean已创建,但自动连接时为空,java,spring,Java,Spring,我正在尝试向类注入一个对象。但是,该字段始终为空。我尝试了@Autowired和@Resource注释。我没有在任何地方使用new操作符创建对象。正确调用Foo的构造函数 此问题的最小示例: Foo类 package foo.bar; public class Foo { Foo(){ System.out.println("Foo constructor"); } public void func() { System.out.print

我正在尝试向类注入一个对象。但是,该字段始终为空。我尝试了
@Autowired
@Resource
注释。我没有在任何地方使用
new
操作符创建对象。正确调用
Foo
的构造函数

此问题的最小示例:

Foo类

package foo.bar;
public class Foo {
    Foo(){
        System.out.println("Foo constructor");
    }
    public void func() {
        System.out.println("func()");
    }
}
package foo.bar;
public class Bar {
    @Autowired
    private Foo foo;

    public Bar() {
        foo.func();
    }
}
酒吧类

package foo.bar;
public class Foo {
    Foo(){
        System.out.println("Foo constructor");
    }
    public void func() {
        System.out.println("func()");
    }
}
package foo.bar;
public class Bar {
    @Autowired
    private Foo foo;

    public Bar() {
        foo.func();
    }
}
入口点

package foo.bar;
public class HelloApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
    }
}
spring config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="foo.bar"/>
    <bean id = "foo" class="foo.bar.Foo" />
    <bean id = "bar" class="foo.bar.Bar" />
</beans>


为什么
Bar
类的
foo
字段总是
null
?如何解决这个问题?

正如@Mick指出的,字段注入必须在构造函数完成后进行(Spring没有其他方法可以查看实例并对其进行操作)。修改类以使用构造函数注入,这样既可以使依赖关系更明确(例如,更易于测试),又可以消除本质上的竞争条件:

public class Bar {
    private Foo foo;

    @Autowired
    public Bar(Foo foo) {
        this.foo = foo;
        foo.func();
    }
}

在字段自动连接之前调用构造函数。因此调用foo.func();在Bar中,构造函数将导致空指针。您可以创建一个方法来调用foo.func();并用@PostConstruct注释它以绕过此问题谢谢,这很好。我只是认为,在声明bean时,Spring中的整个初始化总是(或应该)在xml文件中执行。现在我必须在某处创建Foo对象并将其传递给构造函数。@RK1 Spring知道如何自动连接构造函数。您根本不需要更改XMLBean定义。(如果需要,可以显式地在XML中提供构造函数参数,但只要bean是明确的,Spring就可以为您解析它们。)是的,我不需要更改任何内容。我只是想,在使用Spring时,您不需要在任何地方实例化bean。@RK1您通常不需要,至少是手工实例化,但必须有一些东西来实例化bean,或者它们来自哪里?如果
Bar
不是bean怎么办?我们仍然需要显式地创建一个
Foo
对象,并将其传递给
Bar
构造函数,因此@Autowired变得毫无用处,不是吗