我正在尝试将Map注入UtilityClass。我创建了一个Map Bean,我使用@Resource注释注入它。
@Configuration
class MyConfiguration {
@Bean
Map<String, String> testMap(){
def map = [:] // Using groovy
// Putting things into map
map
}
}
@Component
class MyUtilityClass {
@Resource(name="testMap")
Map<String, String> testMap
}
我收到以下错误:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testMap' defined in com.my.company.config.MyConfiguration: Initialization of bean failed; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.1.5.RELEASE.jar:4.1.5.RELEASE]
.....
Caused by: java.lang.NullPointerException
at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:571) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:490) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:474) ~[spring-core-4.1.5.RELEASE.jar:4.1.5.RELEASE]
在注入Map时我是否在做错了什么。不确定为什么会造成NPE?
更新 - 因此创建了一个类并将Map添加为该类的属性。并将该类注入Bean。它工作正常,它可以在其中注入带有Map的类。
@Configuration
class MyConfiguration {
@Bean
Testclass testClass(){
def map = [:] // Using groovy
// Putting things into map
new TestClass(testMap: map)
}
}
class TestClass {
Map<String, String> testMap
}
所以看起来这个问题出现在Map中。