0

多くのサーブレットを含む大きな Java プロジェクトがあります。また、各サーブレットは、次のコマンドを使用して同じ Bean ファイルからオブジェクトを取得する必要があります。

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

そして、私は使用します

     context.getBean("<BEAN_NAME">);

それらのいくつかは、同じオブジェクトを取得する必要さえあります。

問題は、Bean ファイルを手動で読み取らずに、必要なオブジェクトをサーブレットに直接注入できるかどうかです。

各サーブレットは web.xml で構成されます。

この問題に関する情報をいただければ幸いです。

ありがとう

4

3 に答える 3

2

サーブレットにHttpRequestHandlerを実装することを検討しましたか?

次に、サーブレットを Spring Bean という名前で宣言し、web.xml で同じ名前を使用する必要があります。その後、@Autowired アノテーションを使用して、サーブレットに Spring Bean を注入するだけです。

詳細については、http://www.codeproject.com/Tips/251636/How-to-inject-Spring-beans-into-Servletsを参照してください。

サンプルコード:


  @Component("myServlet") 
   public class MyServlet implements HttpRequestHandler {

        @Autowired
        private MyService myService;
...

サンプル web.xml

<servlet>     
            <display-name>MyServlet</display-name>
            <servlet-name>myServlet</servlet-name>
            <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet
           </servlet-class>
    </servlet>
    <servlet-mapping>
            <servlet-name>myServlet</servlet-name>
            <url-pattern>/myurl</url-pattern>
    </servlet-mapping>
于 2013-07-10T14:00:41.123 に答える
1

メソッドでaSerlvetContextListenerを使用できますServlet#init()。サーブレット コンテナがサーブレット コンテキストを作成すると、アプリケーション シングルトン/Beans/etc の初期化を実行できるcontextInitialized()すべての が呼び出されます。ServletContextListener

public class YourServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // clear context
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // initialize spring context    
        event.getServletContext().setAttribute("context", springContext);
    }
}

このコンテキスト (サーブレット コンテキスト) 内のすべてのサーブレットは、これらの属性にアクセスできます。

Servletinit()メソッドでは、属性を取得するだけです

public class YourServlet implements Servlet {

    @Override
    public void init(ServletConfig config) {
        config.getServletContext().getAttribute("context");
        // cast it (the method returns Object) and use it
    }

    // more
}
于 2013-07-10T13:51:30.240 に答える
1

あなたは Web アプリケーションを持っているので、Web アプリケーションのデプロイ時にロードされ、アンデプロイ時に適切に閉じられる にWebApplicationContext含まれる を使用します。spring-webあなたがしなければならないのはContextLoaderListener、あなたので宣言することだけですweb.xml

<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

次にApplicationContext、任意のサーブレットからアクセスできます。

ApplicationContext ctx = WebApplicationContextUtils
    .getRequiredWebApplicationContext(getServletContext());
MyBean myBean = (MyBean) ctx.getBean("myBean");
myBean.doSomething();

利点は、コンテキストがすべてのサーブレット間で共有されることです。

参考文献:

于 2013-07-10T13:51:37.623 に答える