Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...