qxlab
qxlab

Reputation: 1536

Can't Autowire ServletContext

I'm new with Spring, and I'm trying to use the @Autowire annotation for the ServletContext with my class attribute:

@Controller
public class ServicesImpl implements Services{

    @Autowired
    ServletContext context;

I defined the bean for this class in my dispatcher-servlet.xml:

<bean id="services" class="com.xxx.yyy.ServicesImpl" />

But when I try to run a JUnit test it gives the following error:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.servlet.ServletContext] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I thought that the ServletContext injection was automatic with spring... How can I solve this?

Thanks!

EDIT: I want to use the servletContext to call the getRealPath() method. Is there any alternative?

Upvotes: 23

Views: 32432

Answers (3)

Marcel St&#246;r
Marcel St&#246;r

Reputation: 23535

ServletContext is not a Spring bean and it can, therefore, not be injected unless you implement ServletContextAware.

If one thinks in modules or layers then the servlet context shouldn't be available outside the web module/layer. I suppose your ServicesImpl forms part of the business or service layer.

If you gave a little more context we might be able to suggest better alternatives.

Upvotes: 3

ccheneson
ccheneson

Reputation: 49410

Implement the ServletContextAware interface and Spring will inject it for you

@Controller
public class ServicesImpl implements Services, ServletContextAware{


private ServletContext context;

public void setServletContext(ServletContext servletContext) {
     this.context = servletContext;
}

Upvotes: 29

tstorms
tstorms

Reputation: 5001

You'll probably want to take a look at MockServletContext which can be used in unit tests.

Upvotes: 10

Related Questions