我想使用 Spring 在 Web 应用程序中管理我的 JPA DAO,并尝试按照 Spring 网站示例来弄清楚如何去做。
我正在考虑使用 AnnotationConfigWebApplicationContext
而不是 AnnotationConfigApplicationContext
来引导 Spring。
在示例中,它与 org.springframework.web.servlet.DispatcherServlet
一起使用,但我想在没有 Spring MVC 的情况下使用它。
我的 web.xml 如下所示:
...
<web-app>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.foo.Application</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
...
</web-app>
我的配置类如下所示:
...
@Configuration
@ComponentScan(basePackages={"com.foo.service"})
public class Application {
@Bean
MessageService mockMessageService() {
return new MessageService() {
@Override
public String getMessages() {
return "Hello Spring World!";
}
};
}
}
是否可以将此示例中的 mockMessageService
注入(inject)到我的 servlet 中,或者我是否必须为我的 web 应用程序创建一个单独的中心枢纽,以便 servlet 调用服务?
问题是,如果我在包 com.foo.service
中有我的 servlet 并尝试使用
@Autowired
为了获得依赖性或尝试一些类似的方法,服务没有被注入(inject),我不知道问题出在哪里。有可能那样做吗?或者我应该为 AnnotationConfigWebApplicationContext
添加一些东西来像那样工作吗?
最佳答案
Servlet 由 servlet 容器而不是 spring 管理。 Spring 不会注入(inject) servlet,因为它不会实例化它们。
如果你想在 servlet 中访问由 spring 管理的 bean,你必须像 spring 的 DispatcherServlet
那样做。
例如从 ServletContext
获取 WebApplicationContext
做
javax.servlet.ServletContext servletContext = ...;
WebApplicationContextUtils.getWebApplicationContext(servletContext);
这是有效的,因为 ContextLoaderListener
确保 WebApplicationContext
作为 ServletContext
属性可用。
由于 WebApplicationContext
是一个 ApplicationContext
,您可以 Autowiring 已在 spring 容器外实例化的 bean。
例如
ApplicationContext appContext = ...;
AutowireCapableBeanFactory acbf = context.getAutowireCapableBeanFactory();
SomeBean someBean = new SomeBean();
acbf.autowireBean(someBean);
只需将 @Autowired
注释放在 SomeBean
的字段上即可。
更简单的方法是扩展 spring 的 org.springframework.web.servlet.FrameworkServlet
并实现 doService
方法。阅读 FrameworkServket 的 javadoc了解详情。
关于java - 没有 Spring MVC 的 Spring Web 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25708452/