在Servlet中初始化ApplicationContext

时间:2017-02-28 05:48:14

标签: spring servlets applicationcontext

我正在使用Spring,Hibernate,JSP和Servlets构建应用程序。对于每个表单操作方法,我将值传递给Servlet,并且我声明ApplicationContext在所有servlet中加载spring.xml。有什么办法可以在servlet中的一个地方delcare ApplicationContext并获取所有bean ... < / p>

我宣布

 ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
 Student student = (Student) ac.getBean("student");

我在所有servlet中声明了这一点..是否有任何中心位置来声明这个并在servlet中获取bean ..

1 个答案:

答案 0 :(得分:0)

让Spring在您需要的地方自动装配您的bean。这是做事的首选方式。如果您不熟悉spring中的@Autowired注释,请执行此操作 -

  1. 将此内容添加到您的something-servlet.xml

    <context:component-scan base-package="you_base_package" />
    <mvc:annotation-driven />
    

    your_base_package是包含学生的基础包 您希望自动装配(或实例化)的类和其他类。

  2. 使用@Component为您的学生班级和其他人添加注释。

  3. 使用此选项可在需要时获取学生和其他人的实例。     @Autowired Student student;