获得spring 的bean

一.servlet中
public class HrServlet extends HttpServlet {
    private ApplicationContext applicationContext = null;//定义全局变量context

    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletContext servletContext = config.getServletContext();
        applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    }

    /**
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HrService hrService = (HrService) applicationContext.getBean("hrService");
        String dname = req.getParameter("dname");
        Dept dept = null;
        try {
            dept = hrService.getRecord(dname);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("dept1 = " + dept);
    }
}


二.普通java类中
传统的方法
ApplicationContext context = new ClassPathXmlApplicationContext();

浪费内存,偶尔在 main方法里用一下还可以。

推荐的用法:

1:创建一个类并让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.
/**
 * User: liuwentao
 * Time: 11-7-21 下午3:55
 * <p/>
 * 说明:
 */
public class MyApplicationContextUtil implements ApplicationContextAware {
    private static ApplicationContext context;//声明一个静态变量保存

    /**
     *
     * @param contex
     * @throws BeansException
     */
    public void setApplicationContext(ApplicationContext contex) throws BeansException {
        this.context = contex;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}


2:在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.
<bean class="demo.MyApplicationContextUtil"></bean>


3:在普通java类中调用
HrService hrService = (HrService) MyApplicationContextUtil.getContext().getBean("hrService");


猜你喜欢

转载自wentao365.iteye.com/blog/1129857
今日推荐