Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Autowire ServletContext

Tags:

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?

like image 987
qxlab Avatar asked Feb 15 '13 13:02

qxlab


People also ask

Why is @AutoWired not working in spring?

There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.

When to use @AutoWired in Java?

When @Autowired is used on bean’s constructor, it is also equivalent to autowiring by ‘ constructor ‘ in configuration file. 3. @Qualifier for conflict resolution As we learned that if we are using autowiring in ‘ byType ‘ mode and dependencies are looked for property class types. If no such type is found, an error is thrown.

What is servletcontext interface in Android?

ServletContext Interface. An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application.

How to exclude a bean from autowiring in Java?

If you want to make specific bean autowiring non-mandatory for a specific bean property, use required=”false” attribute in @Autowired annotation. If you want to apply optional autowiring at global level i.e. for all properties in all beans; use below configuration setting. 5. Excluding a bean from autowiring


1 Answers

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; } 
like image 181
ccheneson Avatar answered Sep 29 '22 14:09

ccheneson