2013-10-06 5 views
0

Возможно ли иметь один и тот же ресурс в двух разных классах, которые находятся в двух разных сервлетах?Тот же ресурс в двух разных сервлетах

Я хочу сделать что-то вроде этого:

public class One{ 
     @Resource(name="subscriptionService") 
    private SubscriptionService subscriptionService; 
} 

public class Two{ 
     @Resource(name="subscriptionService") 
    private SubscriptionService subscriptionService; 
} 

@Service("subscriptionService") 
@Transactional 
public class SubscriptionService { 
} 

Есть два различных сервлета для класса одного и класса два, так что два разных экземпляра SubscriptionService. Есть ли способ сделать это?

EDIT:

web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 

    <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> 
    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/spring/root-context.xml</param-value> 
    </context-param> 

    <!-- Creates the Spring Container shared by all Servlets and Filters --> 
    <listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 

    <!-- Processes application requests --> 
    <servlet> 
     <servlet-name>appServlet</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
      <param-name>contextConfigLocation</param-name> 
      <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>appServlet</servlet-name> 
     <url-pattern>/</url-pattern> 
    </servlet-mapping> 

    <servlet> 
     <servlet-name>member-ws</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <init-param> 
       <param-name>transformWsdlLocations</param-name> 
       <param-value>true</param-value> 
     </init-param> 
    </servlet> 

    <servlet-mapping> 
     <servlet-name>member-ws</servlet-name> 
     <url-pattern>/services/*</url-pattern> 
    </servlet-mapping> 


</web-app> 

член-WS-servlet.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:oxm="http://www.springframework.org/schema/oxm" 
    xmlns:sws="http://www.springframework.org/schema/web-services" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

    <!-- Activates various annotations to be detected in bean classes --> 
    <context:annotation-config /> 
    <context:component-scan base-package="pl.pk.edu" /> 

    <!-- Uses the latest feature from 2.0.0 RC2. 
     Enables @Endpoint and related Spring-WS annotations. See Spring WS Reference 5.4--> 
    <sws:annotation-driven /> 

    <!--<context:component-scan base-package="pl.pk.edu" />--> 
    <!-- SAAJ-specific implementation of the WebServiceMessageFactory. Wraps a SAAJ MessageFactory. 
    This factory will use SAAJ 1.3 when found, or fall back to SAAJ 1.2 or even 1.1. --> 
    <beans:bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/> 

    <!-- Requires a message factory so we declare one --> 
    <beans:bean class="org.springframework.ws.transport.http.WebServiceMessageReceiverHandlerAdapter" 
      p:messageFactory-ref="messageFactory"/> 

    <!-- See reference at the beginning of this document --> 
    <beans:bean class="org.springframework.ws.transport.http.WsdlDefinitionHandlerAdapter"/> 

    <!-- This is responsible for forwarding web service request to the correct adapters. 
    This is exactly similar to Spring MVC's DispatcherServlet --> 
    <beans:bean id="messageDispatcher" class="org.springframework.ws.server.MessageDispatcher"> 
      <beans:property name="endpointAdapters"> 
       <beans:list> 
        <beans:ref bean="defaultMethodEndpointAdapter"/> 
       </beans:list> 
      </beans:property> 
    </beans:bean> 

    <!-- See reference at the beginning of this document --> 
    <beans:bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 
     <beans:property name="mappings"> 
      <beans:value> 
       /ws=messageDispatcher 
       /ws/subscription.wsdl=subscription 
      </beans:value> 
     </beans:property> 
    </beans:bean> 

    <!-- See reference at the beginning of this document --> 
    <beans:bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> 

    <!-- Uses the latest feature from 2.0.0 RC2. 
     Enables interceptor endpoints. See Spring WS Reference 5.5.2 
     Here we have an interceptor that validates XML request and a logger 
     --> 
    <sws:interceptors> 
      <beans:bean id="validatingInterceptor" class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor" 
         p:schema="/WEB-INF/spring/wsServlet/subscription.xsd" 
         p:validateRequest="true" 
         p:validateResponse="true"/> 

      <beans:bean id="loggingInterceptor" class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/> 
    </sws:interceptors> 

    <!-- Uses the latest feature from 2.0.0 RC2. 
     Enables publishing of wsdl. See Spring WS Reference 3.7 
     For dynamic location transformation to work, a special parameter must be added to the web.xml. 
     The locationUri here has no use when integrated with Spring MVC because 
     it has been overriden by the SimpleUrlHandlerMapping --> 
    <sws:dynamic-wsdl id="subscription"               
     portTypeName="SubscriptionPort"               
     locationUri="/"              
     targetNamespace="http://www.example.org/subscription">        
     <sws:xsd location="/WEB-INF/spring/wsServlet/subscription.xsd"/>             
    </sws:dynamic-wsdl> 

    <!-- Our mashaller. You can use any marshaller you want. 
    For info on how to use Castor, see http://www.castor.org/xml-mapping.html#2.1-Marshalling-Behavior --> 
    <beans:bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller" 
     p:mappingLocation="/WEB-INF/spring/wsServlet/castor-mapping.xml" /> 

    <!-- Normally we use the GenericMarshallingMethodEndpointAdapter however if you read the Spring WS 2.0 API for this adapter: 
    "Deprecated. as of Spring Web Services 2.0, in favor of DefaultMethodEndpointAdapter and MarshallingPayloadMethodProcessor." 
    See http://static.springsource.org/spring-ws/sites/2.0/apidocs/org/springframework/ws/server/endpoint/adapter/GenericMarshallingMethodEndpointAdapter.html 

    So we have to implement using the recommended implementation. The advantage of these two classes is that 
    we have a pluggable adapter. For more info, check the Spring WS 2.0 API and its source code. 
    --> 
    <beans:bean id="marshallingPayloadMethodProcessor" class="org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor"> 
     <beans:constructor-arg ref="castorMarshaller"/> 
     <beans:constructor-arg ref="castorMarshaller"/> 
    </beans:bean> 

    <beans:bean id="defaultMethodEndpointAdapter" class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter"> 
     <beans:property name="methodArgumentResolvers"> 
      <beans:list> 
       <beans:ref bean="marshallingPayloadMethodProcessor"/> 
      </beans:list> 
     </beans:property> 
     <beans:property name="methodReturnValueHandlers"> 
      <beans:list> 
       <beans:ref bean="marshallingPayloadMethodProcessor"/> 
      </beans:list> 
     </beans:property> 
    </beans:bean> 

</beans:beans> 

сервлет-context.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans:beans xmlns="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:oxm="http://www.springframework.org/schema/oxm" 
    xmlns:web-services="http://www.springframework.org/schema/web-services" 
    xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd 
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 
    <context:annotation-config /> 
    <context:component-scan base-package="pl.pk.edu" /> 
    <!-- Enables the Spring MVC @Controller programming model --> 
    <annotation-driven /> 

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
    <resources mapping="/resources/**" location="/resources/" /> 

    <!-- Wczytanie beansow dla tiles oraz plikow konfiguracyjnych --> 
    <beans:bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver" /> 
    <beans:bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> 
    <beans:property name="definitions"> 
     <beans:list> 
      <beans:value>/WEB-INF/tiles.xml</beans:value> 
     </beans:list> 
    </beans:property> 
    </beans:bean> 

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <beans:property name="prefix" value="/WEB-INF/views/" /> 
     <beans:property name="suffix" value=".jsp" /> 
    </beans:bean> 



</beans:beans> 
+0

Зависит от конфигурации контекста. Отправьте его, как web.xml, так и ваш контекст Spring. –

+0

Да, вы можете. Вы хотя бы пробовали? –

+0

Я добавил, извините за беспорядок в коде – John

ответ

0

Если SubscriptionService определен в вашем root-context.xml, тогда он должен работать.

Поэтому вам нужно изменить вам компонент сканирования, так что:

  • компонент сканирования в root-context.xml находит эту услугу, но не One или Two нет контроллера боба и
  • компонент сканирования из двух сервлеты найти One/Two но не SubscriptionService

Typicaly это это делается путем фильтрации (включения и исключения) по Аннотации:

root-context.xml:

<context:component-scan base-package="yourPackage"> 
    <context:exclude-filter 
      expression="org.springframework.stereotype.Controller" 
      type="annotation" /> 
</context:component-scan> 

servlet-context.xml:

<context:component-scan base-package="yourPackage" use-default-filters="false"> 
     <context:include-filter 
       expression="org.springframework.stereotype.Controller" 
       type="annotation" /> 
</context:component-scan> 
0

У вас есть два DispatcherServlet экземпляры bu t хочу один SubscriptionService bean. Измените конфигурацию в обоих файлах контекста сервлета, чтобы они не component-scan класс SubscriptionService. Вместо этого поставьте component-scan в контексте приложения root-context.xml, загруженном ContextLoaderListener.

С DispatcherServlet использует контекст, загруженный ContextLoaderListener, бонусы, объявленные там, будут доступны для него.

Смежные вопросы