2013-02-06 5 views
7

SpringとJerseyの両方を使用するServlet 3.0 Webアプリケーションがあります。私は現在、web.xmlのフィルタとして設定されたSpringServletと、@Path@Componentの両方で注釈が付けられたリソースクラスを使用して設定しています。ここでのweb.xmlの抜粋です:Annotationのみを使用してSpringでJerseyを設定する方法

<filter> 
    <filter-name>jersey-serlvet</filter-name> 
    <filter-class> 
     com.sun.jersey.spi.spring.container.servlet.SpringServlet 
    </filter-class> 
    <init-param> 
     <param-name> 
      com.sun.jersey.config.property.packages 
     </param-name> 
     <param-value>com.foo;com.bar</param-value> 
    </init-param> 
    <init-param> 
     <param-name>com.sun.jersey.config.feature.FilterForwardOn404</param-name> 
     <param-value>true</param-value> 
    </init-param> 
</filter> 

<filter-mapping> 
    <filter-name>jersey-serlvet</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

このセットアップは動作しますが、私は本当にこれが唯一の注釈で設定を取得したい - なしのweb.xmlの設定。私の最初の試みは、上記のSpringServlet設定を削除し、Applicationを拡張するクラスを作成することでした。ここではその抜粋です:

@ApplicationPath("/*") 
public class MyApplication extends PackagesResourceConfig { 

    public MyApplication() { 
     super("com.foo;com.bar"); 

     HashMap<String, Object> settings = new HashMap<String, Object>(1); 
     settings.put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, true); 
     this.setPropertiesAndFeatures(settings); 
    } 
} 

これは、JAX-RSリソースが登録されていることで動作し、私はそのURLでそれらを打つことができますが、彼らは試してみて、自分のautowiredプロパティを使用するとき、彼らはNullPointerExceptionsがを投げる...これは作りますなぜなら、リソースは現在Jerseyによってロードされており、Spring管理beanではないと推測しているので、autowiringはありません。

Jerseyのリソースを注釈付きのSpring Beanとしてロードする方法はありません。 このような方法がありますか? Springコンテキストを手動でフェッチし、私がそれを助けることができるなら、DIを呼び出すためのリソースのコードを書く必要はありません。

注釈のみが動作しない場合、スキャンするパッケージのリストの代わりにApplicationクラスを指定することができれば、web.xmlにフィルタ設定で保存できます。私がパッケージリストを取り除いてApplicationクラスインスタンスを指定することができれば、私は満足できるでしょう。

明らかに誰かが私にとって決定的な答えを持っていれば素晴らしいかもしれませんが、私は他にどこに見えるか、試してみるべき点やヒントについても感謝しています。

おかげで、 マット

答えて

1

は、私は私の理想的な結果を得ることができていないが、私はいくつかの進歩を遂げることができたので、それは他の誰を助け場合、私はここに投稿します。 Spring Servletを使用してアプリケーションクラスを指定することで、web.xmlからパッケージリストを削除できました。

必要なのweb.xmlの変更は、初期化のparams(フィルタマッピングが示されていないが、それでも必要です)にあります。

<filter> 
    <filter-name>jersey-serlvet</filter-name> 
    <filter-class> 
     com.sun.jersey.spi.spring.container.servlet.SpringServlet 
    </filter-class> 
    <init-param> 
     <param-name>javax.ws.rs.Application</param-name> <!-- Specify application class here --> 
     <param-value>com.foo.MyApplication</param-value> 
    </init-param> 
</filter> 

そしてアプリケーションクラスで私はと呼ばれる方法を変更しなければなりませんでしたわずかスーパーコンストラクタ:まだ

public MyApplication() { 
    super("com.foo", "com.bar"); // Pass in packages as separate params 

    HashMap<String, Object> settings = new HashMap<String, Object>(1); 
    settings.put(ServletContainer.FEATURE_FILTER_FORWARD_ON_404, true); 
    this.setPropertiesAndFeatures(settings); 
} 

ない、まさに私が後だったが、少なくとも、これはJavaコードに変換し、私は非表示しようとしているとして、私のために重要であるのweb.xmlのうちもう少し設定を引っ張りますこの詳細。

1

2つのオプションが念頭に置いてあります。

  1. あなた自身のクラスでSpringServletを拡張し、適切なサーブレット3.0アノテーションを追加することもできます。
  2. SpringServletからApplicationクラスに切り替えるアプローチに沿って、Springビルド時間またはロード時バイトコード織りを有効にすることによって、オートワイヤリングの問題を解決できます。これにより、Springは、Springによって作成されたオブジェクトだけでなく、どこからでもインスタンス化されたオブジェクトを挿入できます。 "Using AspectJ to dependency inject domain objects with Spring"を参照してください。
1

まず、サーブレット3.0コンテナでは、実際にはweb.xmlは必要ありません。

しかしジャージー2.0で、あなたは注釈を付けたリソースのための全体のウェブアプリをスキャンするためにフラグを設定することができます:あなたは、このjarファイルが含まれている場合

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

<servlet> 
    <servlet-name>jersey</servlet-name> 
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> 
    <init-param> 
     <param-name>jersey.config.servlet.provider.webapp</param-name> 
     <param-value>true</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

春が自動的に有効になります。以下は

<dependency> 
     <groupId>org.glassfish.jersey.ext</groupId> 
     <artifactId>jersey-spring3</artifactId> 
     <version>2.3.1</version> 
    </dependency> 
+0

おかげ

// Specifies that there will be bean methods annotated with @Bean tag // and will be managed by Spring @Configuration // Equivalent to context:component-scan base-package="..." in the xml, states // where to find the beans controlled by Spring @ComponentScan(basePackages = "config.package") public class AppConfig { /** * Where will the project views be. * * @return ViewResolver como el XML */ @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); return viewResolver; } } 

Hibernate設定が、私はニュージャージー1使用していると私はトラブルになっていない:config.package

public class WebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) { // Don't create the Listener that Jersey uses to create. // There can only be one linstener servletContext.setInitParameter("contextConfigLocation", "<NONE>"); AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); // Add app config packages context.setConfigLocation("config.package"); // Add listener to the context servletContext.addListener(new ContextLoaderListener(context)); // Replacing: // <servlet-name>ServletName</servlet-name> // <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class> // <init-param> // <param-name>com.sun.jersey.config.property.packages</param-name> // <param-value>webservices.packages</param-value> // </init-param> // <load-on-startup>1</load-on-startup> AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); ServletRegistration.Dynamic appServlet = servletContext.addServlet("ServletName", new DispatcherServlet(dispatcherContext)); appServlet.setInitParameter("com.sun.jersey.config.property.packages", "org.sunnycake.aton.controller"); appServlet.setLoadOnStartup(1); appServlet.addMapping("/RootApp"); } } 

設定クラスがありますJerseyのリソースがロードされ実行されています。私がautowiringするように、私はそれらが春に管理されることが問題です。 – Doughnuts

+0

この場合、これはあなたにとって解決策ではありません。しかし、これはSpringのautowiringを可能にします。 – rustyx

2

ですServlet 3.0、Spring、Jersey 1.8を使用する私のアプリケーションの一部。web.xmlはありません:

public class WebAppInitializer implements WebApplicationInitializer { 

@Override 
public void onStartup(ServletContext servletContext) throws ServletException { 
    final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); 
    context.setConfigLocation("com.myapp.config"); 

    final FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter()); 
    characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); 
    characterEncodingFilter.setInitParameter("encoding", "UTF-8"); 
    characterEncodingFilter.setInitParameter("forceEncoding", "true"); 

    final FilterRegistration.Dynamic springSecurityFilterChain = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); 
    springSecurityFilterChain.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); 

    servletContext.addListener(new ContextLoaderListener(context)); 
    servletContext.setInitParameter("spring.profiles.default", "production"); 

    final SpringServlet servlet = new SpringServlet(); 

    final ServletRegistration.Dynamic appServlet = servletContext.addServlet("appServlet", servlet); 
    appServlet.setInitParameter("com.sun.jersey.config.property.packages", "com.myapp.api"); 
    appServlet.setInitParameter("com.sun.jersey.spi.container.ContainerRequestFilters", "com.myapp.api.SizeLimitFilter"); 
    appServlet.setLoadOnStartup(1); 

    final Set<String> mappingConflicts = appServlet.addMapping("/api/*"); 

    if (!mappingConflicts.isEmpty()) { 
     throw new IllegalStateException("'appServlet' cannot be mapped to '/' under Tomcat versions <= 7.0.14"); 
    } 
} 

}

0

SpringMVCを使用して以前作成したプロジェクトでJerseyを使用しました。私のコードはSpring's official documentationに基づいています。あなたの答えのための

// Specifies that there will be bean methods annotated with @Bean tag 
// and will be managed by Spring 
@Configuration 
// Equivalent to Spring's tx in the xml 
@EnableTransactionManagement 

// Equivalent to context:component-scan base-package="..." in the xml, states 
// where to find the beans controlled by Spring 
@ComponentScan({"config.package"}) 

// Here it can be stated some Spring properties with a properties file 
@PropertySource(value = {"classpath:aplicacion.properties"}) 
public class HibernateConfig { 

    /** 
    * Inyected by Spring based on the .properties file in the 
    * \@PropertySource tag. 
    */ 
    @Autowired 
    private Environment environment; 

    /** 
    * Here it's created a Session Factory, equivalent to the Spring's config file one. 
    * 
    * @return Spring Session factory 
    */ 
    @Bean 
    public LocalSessionFactoryBean sessionFactory() { 
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 

     // Uses the datasource 
     sessionFactory.setDataSource(dataSource()); 

     // Indicates where are the POJOs (DTO) 
     sessionFactory.setPackagesToScan(new String[]{"dto.package"}); 
     // Se asignan las propiedades de Hibernate 
     sessionFactory.setHibernateProperties(hibernateProperties()); 

     return sessionFactory; 
    } 

    /** 
    * Propiedades de la base de datos (Según environment) 
    * 
    * @return Nuevo DataSource (Configuración de la base de datos) 
    */ 
    @Bean 
    public DataSource dataSource() { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); 
     dataSource.setUrl(environment.getRequiredProperty("jdbc.url")); 
     dataSource.setUsername(environment.getRequiredProperty("jdbc.username")); 
     dataSource.setPassword(environment.getRequiredProperty("jdbc.password")); 
     return dataSource; 
    } 

    /** 
    * Hibernate properties 
    * 
    * @return Properties set with the configuration 
    */ 
    private Properties hibernateProperties() { 
     Properties properties = new Properties(); 
     // Dialect (Mysql, postgresql, ...) 
     properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect")); 
     // Show SQL query 
     properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql")); 
     properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql")); 
     return properties; 
    } 

    /** 
    * Inyected by sessionFactory 
    */ 
    @Bean 
    @Autowired 
    public HibernateTransactionManager transactionManager(SessionFactory s) { 
     HibernateTransactionManager txManager = new HibernateTransactionManager(); 
     txManager.setSessionFactory(s); 
     return txManager; 
    } 
} 
関連する問題