如何用Spring将Service注入到Servlet中
2017-03-19 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
在applicationContext.xml中定义数据层访问Bean:
<bean id="userDao" class="test.UserDaoImpl"></bean>
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
....
}
注入方法::在Servlet的init方法中增加以下代码:
public void init(ServletConfig config) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
并且在变量userDao上一行增加@Autowired:
<a href="https://www.baidu.com/s?wd=%40Autowired&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YznAf1nHwhP1f1nymsPvcz0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPHmknj0vPjcdPWbYn1DvPHmY" target="_blank" class="baidu-highlight">@Autowired</a>
private UserDao userDao;
<bean id="userDao" class="test.UserDaoImpl"></bean>
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
....
}
注入方法::在Servlet的init方法中增加以下代码:
public void init(ServletConfig config) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
并且在变量userDao上一行增加@Autowired:
<a href="https://www.baidu.com/s?wd=%40Autowired&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YznAf1nHwhP1f1nymsPvcz0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPHmknj0vPjcdPWbYn1DvPHmY" target="_blank" class="baidu-highlight">@Autowired</a>
private UserDao userDao;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询