我有以下结构的行家项目:来自不同Maven模块的Autowire类?
spring-di-test
+--spring-di-test-core
| com.example.core.DITestMain
+--spring-di-test-store
com.example.store.DITest
com.example.store.RandomStringService
其中弹簧二叔测试是根项目和下面的两个是模块。
我的课是这样的:位于春二测试核心
DITestMain
public class DITestMain {
public static void main(String[] args) {
new DITest().run();
}
}
的applicationContext.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/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-sto再位于弹簧二叔测试店内
@Configurable(preConstruction = true)
@Controller
public class DITest {
@Autowired(required=true)
private RandomStringService randomStringService;
public void run() {
System.out.println(randomStringService.getRandomString());
}
}
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位于弹簧二叔测试店内
<?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。什么地方出了错?
1.我可以使用注释或XML创建上下文吗? 2.如何配置和启用加载时编织? – Gorkamorka
1:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-instantiation 2:看,我贴在我的答案链接。 – pap