I have a maven project with the following structure:
spring-di-test
+--spring-di-test-core
| com.example.core.DITestMain
+--spring-di-test-store
com.example.store.DITest
com.example.store.RandomStringService
where spring-di-test is the root project and the two below are modules.
My classes look like this:
DITestMain located in spring-di-test-core
applicationContext.xml located in spring-di-test-core's resources folderCode:public class DITestMain { public static void main(String[] args) { new DITest().run(); } }
DITest located in spring-di-test-storeCode:<?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>
RandomStringService located in spring-di-test-storeCode:@Configurable(preConstruction = true) @Controller public class DITest { @Autowired(required=true) private RandomStringService randomStringService; public void run() { System.out.println(randomStringService.getRandomString()); } }
applicationContext.xml located in spring-di-test-storeCode:@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(); } }
When I run DITestMain, I get a NullPointerException for randomStringService. What went wrong?Code:<?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>


Reply With Quote
