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?
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 @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.
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.
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
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With