0

我是春天的新手。使用 jdk 1.7。我定义了一个类:

public class FileDetails {

String filePath;
String fineName;
String timeStamp;

    public FileDetails(String filePath, String fineName, String timeStamp) {
    this.filePath = filePath;
    this.fineName= fineName;
    this.timeStamp = timeStamp;
}

}

并尝试从与以下相同的包中的另一个类创建此类的列表:

public class otherClass{

    @Autowired
private List<FileDetails> fileInfo;

    public void addToList(){
        fileInfo.add(new FileDetails("something","something","something");
   }
}

这是我的应用程序上下文:

 <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-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>



<bean id="fileDetails" class="pacckageName.FileDetails" >
</bean>

</beans>

我收到错误:

 null pointer exception on the line "fileInfo.add(new FileDetails("something","something","something");"

我在哪里做错了?

4

1 回答 1

0

OtherClass不是托管bean。您可能正在new OtherClass()代码中的某个地方做某事。

托管 bean 是由 Spring 管理的实例,因为它要么是

  • 通过组件扫描发现(在您的应用程序上下文中使用组件扫描指令进行OtherClass注释)@Component
  • 在应用程序上下文中显式创建(即在您的FileDetailsbean 旁边)

当您运行时new OtherClass(),它是您创建的常规实例,Spring 不知道您创建了它,并且它无法处理诸如此类的注释@Autowired

因此,您最终会得到一个实例,就像 Spring 根本不存在一样,并且如您所见,您的列表因此是null.

@Autowiredon a collection 定位该集合类型的所有托管bean 并将它们收集到注入的集合中。required如果未找到任何项目,除非您将注释的标志设置为 ,否则将引发异常false

最后一点,您的示例 forFileDetails没有空构造函数,并且您的 bean 定义也没有提供任何参数。这不应该工作,我猜你在描述中删除了部分代码。

于 2014-05-15T07:43:22.867 回答