簡體   English   中英

在Servlet中使用@Autowire

[英]Use @Autowire in servlet

我想在我的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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM