基于注释的注入;初始化空映射



我正在使用基于弹簧>注释的注入

@Component
public class MyClass {
    private ConcurrentHashMap<String, String> myMap;
    public MyClass() {
        myMap = new ConcurrentHashMap<String, String>();
    }
    public void foo() {
        myMap.put("a", "b");
    }
}

.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/context
             http://www.springframework.org/schema/context/spring-context-3.0.xsd
             http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
          <context:component-scan base-package="com.basePackage" />
          <context:annotation-config/>
    </beans>

主() 类

public class MyMain() {
    public static void main(String[] args)
    // [EDITED. ADDED NOW - BEGIN]
    ApplicationContext context = new GenericXmlApplicationContext(
        "myApplicationContext.xml");
    // [EDITED. ADDED NOW - END]
        MyClass myObj = (MyClass) context.getBean(MyClass.class);
        myObj.foo();
    }
}

myObj.foo() 会引发一个 NPE。我期待:当我得到bean时,map的构造函数被调用,map被实例化,代码运行流畅。

这都不起作用:
private ConcurrentHashMap myMap = new ConcurrentHashMap();

我如何让这段代码工作。注意:

  • 我不想在 xml 中添加部件配置,在 java 中添加部件配置。我也试图用一张空地图实例化。
  • 我想让它以注释方式本身工作,并在我第一次使用它之前将地图实例化为空。

您可能不会向我们展示所有详细信息。例外不是因为您的ConcurrentHashMap null。发生这种情况是因为您在put()方法调用中传递了一个null对象。ConcurrentHashMap类不支持null键。javadoc 状态

与 Hashtable 类似,但与 HashMap 不同,此类不允许 null 到 用作键或值。

除非上下文为空,否则此处不能有 NPE。如果没有MyClass.class则在上下文中将抛出NoSuchBeanDefinitionException。如果你设法让 bean 获得上下文,那么它就会被初始化,myMap 是一个空的映射。寻找其他地方的问题

first:你需要 setter & getter in myClass for the field myMap。第二:你不会在MyClass中使用myMap的新操作,因为

MyClass myObj = (MyClass) context.getBean(MyClass.class);

进行注入,当然也为其分配内存。

最新更新