Hi Everyone,
I am currently refactoring an existing application to use component scanning and auto wiring to reduce the amount of xml configuration it has.
I have stumbled across a problem this morning that has got me stumped and was hoping someone could help?
I am simply trying to Auto wire a bean on the class attribute, but get a null pointer exception. The bean that I am trying to auto wire is created using component scanning and it is instantiated when I run through debug (breakpoint on the constructor). The weird thing is, that if I try to @Autowired on the constructor or a setter it finds the bean ok..
I created a small test class to demonstrate
web.xml
Code:<context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/test2.xml /WEB-INF/test.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
Test.xml
Class created by component scanCode:<?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" xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="uk.co.test" /> </beans>
Now in this testAutowire below which is created from component scan in test2.xml I try to autowire but get a null pointer?Code:@Component public class myTest { private Logger logger = Logger.getLogger(this.getClass()); public myTest() { logger.info("test class created by component scan"); } }
However if I add it to the constructor or a setter it works i.eCode:@Component public class testAutowire { @Autowired private myTest myTest; public testAutowire () { System.out.println("testAutowire"); } }
Can anyone advise please?Code:@Autowired public testAutowire (myTest myTest) { System.out.println("testAutowire"); }


Reply With Quote