我有一个具有以下结构的 Maven 项目:
spring-di-test
+--spring-di-test-core
| com.example.core.DITestMain
+--spring-di-test-store
com.example.store.DITest
com.example.store.RandomStringService
其中 spring-di-test 是根项目,下面两个是模块。
我的课程如下所示:
DITestMain 位于 spring-di-test-core
public class DITestMain {
public static void main(String[] args) {
new DITest().run();
}
}
applicationContext.xml 位于 spring-di-test-core 的资源文件夹中
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:spring-configured/>
<context:component-scan base-package="com.example.*" annotation-config="true"/>
</beans>
DITest 位于 spring-di-test-store
@Configurable(preConstruction = true)
@Controller
public class DITest {
@Autowired(required=true)
private RandomStringService randomStringService;
public void run() {
System.out.println(randomStringService.getRandomString());
}
}
位于 spring-di-test-store 中的 RandomStringService
@Service("randomStringService")
public class RandomStringService {
private final Random random;
public RandomStringService() {
random = new Random();
}
public String getRandomString() {
StringBuilder sb = new StringBuilder();
int length = random.nextInt(20);
for (int i = 0; i < length + 1; i++) {
sb.append(new Character((char) ('a' + random.nextInt(20))));
}
return sb.toString();
}
}
applicationContext.xml 位于 spring-di-test-store
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:spring-configured/>
<context:component-scan base-package="com.example.*" annotation-config="true"/>
</beans>
当我运行 DITestMain 时,我得到了 randomStringService 的 NullPointerException。什么地方出了错?