Hi there,
I'm trying to create a simple Spring example using beans and annotations, but my @Autowired does not seem to work, nor does the container seem to instantiate my bean automatically. This is what I did:
1. In web.xml, set up a org.springframework.web.context.ContextLoaderListe ner and pointed the contextConfigLocation listener to by XML doc, /WEB-INF/spring-context.xml
2. Created spring-context.xml in such a way that the entire system uses annotation-based configuration and set up the "base-package" as the lowest common denominator as follows:
3. Set up a @Service Service Bean - which doesn't get instantiated...Code:<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/schem...-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config base-package="com.foxbomb.springtest"/> </beans>as such:
4. Then I set up a class, that every time I instantiate it, realizes that it's a Spring configured class (annotated with @configurable), and injects the dependencies automatically. This is TimeManager.class. Here the @Autowired dependency seems to fail:Code:package com.foxbomb.springtest.domain.time; import java.util.Date; import org.springframework.stereotype.Service; @Service public class TimeService { public TimeService() { System.out.println("Instantiating Time Service"); } public Date getTime() { return new Date(); } }
5. Then I created a JSP, for the simple purpose of interrogating the TimeManager class. Instantiating the TimeManager class in the JSP I hoped, would wake up Spring (cause it's @configurable) and quickly inject the protected TimeService timeService dependency in for me. Alas, the JSP reports a NullPointerException at return timeService.getTime();Code:package com.foxbomb.springtest; import com.foxbomb.springtest.domain.time.TimeService; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Configurable public class TimeManager { public TimeManager() { System.out.println("Instantiating Time Manager"); } @Autowired protected TimeService timeService; public Date getTime() { return timeService.getTime(); } }
What am I doing wrong? Your help is greatly appreciated...Code:<%@page import="com.foxbomb.springtest.ApplicationContextImpl"%> <%@page import="com.foxbomb.springtest.TimeManager"%> <%! TimeManager manager = new TimeManager(); %> <html> <body> <h1>Autowired Dependencies....</h1> <p> Time is now <%=manager.getTime()%>! </p> </body> </html>


as such:
Reply With Quote
..
