我想在我的servlet中使用@Autowired
引入一些外部配置。
这是我的servlet
public class DashboardServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String USER_AGENT = "Mozilla/5.0";
private String backendUserPassword="";
public DashboardServlet() {
super();
}
private WebApplicationContext springContext;
@Autowired
BackendHostConfiguration backendHostConfiguration;
public void init(ServletConfig config) throws ServletException {
super.init(config);
springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
final AutowireCapableBeanFactory beanFactory = springContext.getAutowireCapableBeanFactory();
beanFactory.autowireBean(this);
backendUserPassword = backendHostConfiguration.getUserpassword();
}
protected void doGet...
但是,我的backenHostConfiguration始终为null。有人能帮我吗?
这是我的web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<description></description>
<display-name>DashboardServlet</display-name>
<servlet-name>DashboardServlet</servlet-name>
<servlet-class>com.apple.store.unifiedproj.proxyapi.DashboardServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DashboardServlet</servlet-name>
<url-pattern>/dashboard/*</url-pattern>
</servlet-mapping>
最佳答案
将Servlet声明为Spring bean。在web.xml中声明一个与Bean具有相同名称的servlet。