Spring Bean未使用AnnotationConfigApplicationContext自动连接

Spring Bean未使用AnnotationConfigApplicationContext自动连接,spring,spring-annotations,Spring,Spring Annotations,我对Spring2.5之后引入的注释驱动Spring相当陌生。我对基于XML的配置相当满意,而且我从未遇到过任何问题,让Bean使用加载Spring容器的XML方法自动连接。XML世界的一切都很酷,但后来我转向注释Ville,现在我有一个快速的问题要问这里的人们:为什么我的bean不会自动连线?以下是我创建的类: import org.springframework.beans.factory.annotation.Autowired; import org.springframework.co

我对Spring2.5之后引入的注释驱动Spring相当陌生。我对基于XML的配置相当满意,而且我从未遇到过任何问题,让Bean使用加载Spring容器的XML方法自动连接。XML世界的一切都很酷,但后来我转向注释Ville,现在我有一个快速的问题要问这里的人们:为什么我的bean不会自动连线?以下是我创建的类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.myspringapp.MyBean;
import com.myspringapp.MySpringAppConfig;

public class TestConfig {

@Autowired
private static MyBean myBean;

public static void main(String[] args) {
    new AnnotationConfigApplicationContext(MySpringAppConfig.class);
    System.out.println(myBean.getString());
}

}
上面是调用AnnotationConfigApplicationContext类的标准java类。我的印象是,一旦加载了“MySpringAppConfig”类,我就可以引用myBean的aurowired属性,因此就可以对其调用getString方法。然而,我总是得到null,因此得到NullPointerException

package com.myspringapp;

import org.springframework.stereotype.Component;

@Component
public class MyBean {

    public String getString() {
        return "Hello World";
    }
}
上面是组件MyBean,它很容易理解,下面是配置类:

package com.myspringapp;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MySpringAppConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

注意:如果我使用(MyBean)ctx.getBean(“MyBean”),我就能够获得对bean的引用;但是我不想使用getBean方法。

我知道的唯一方法是自动关联静态字段,就是使用setter。但是这在您的情况下也不起作用,因为Spring需要处理对象,但是
TestConfig
类在您的代码中没有处理。如果要将依赖项注入
TestConfig
,可以将其定义为bean:

public class MySpringAppConfig {
  @Bean
  public TestConfig testConfig() {
    return new TestConfig();
  }
  .....
然后通过以下途径获取:

TestConfig tc = (TestConfig) ctx.getBean("testConfig");

然后Spring可以使用setter方法注入
myBean

@Autowire
可以在Spring管理的bean中自动连接Spring管理的bean。但是
TestConfig
不是由Spring管理的!所以,您的意思是,我将这个PSVM类作为JUnit测试类,并使用RunWith(SpringJUnit…)类?这将由Spring管理吗?Peter我能够将这个类作为测试类运行,JUnit通过,这意味着myBean属性已经自动连接,并且我能够断言getString方法。现在,我想知道当我向类中添加以下代码时,它到底有什么不同:@ContextConfiguration(classes=MySpringAppConfig.class)@RunWith(SpringJUnit4ClassRunner.class)