Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

spring - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...