Friday 22 April 2011

Access from Servlet Spring @Autowired/@Resource


access @Autowired

public class RSSServlet extends HttpServlet {

 private static NewsService newsService;
 private static ApplicationContext ctx;
 private static String[] configs = {"classpath:applicationContext.xml"};

 static {
  ctx = new ClassPathXmlApplicationContext(configs);
  newsService = (NewsService)ctx.getBean("newsService");
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //...
 }

}


==========================================

access @Resource

public class RSSServlet extends HttpServlet {

 private static Properties config;
 private static ApplicationContext ctx;
 private static String[] configs = {"classpath:applicationContext.xml"};
 private static String domain;

 static {
  ctx = new ClassPathXmlApplicationContext(configs);
  config = (Properties)ctx.getBean("runtimeConfig");
  domain = (String) config.get("domain");
  System.out.println("*** domain="+domain);
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //...
 }

}


No comments:

Post a Comment