【问题标题】:Programmatic integration of Spring 4 and jersey [duplicate]Spring 4和球衣的程序化集成[重复]
【发布时间】:2017-02-04 10:29:12
【问题描述】:

如何在球衣资源中自动装配 spring bean?

我正在尝试拼凑一个球衣应用程序,该应用程序使用 spring 来初始化 jax-rs 资源中的字段。从谷歌搜索来看,这似乎是可能的,但它们始终为空。我的 bean 被创建但没有被注入。

我的 REST 资源

@Path ("/clips")
@Component
public class ClipStreamService {

  @Autowired 
  private ClipHandler clipHandler;

  @GET
  public Response defaultGet() {
    Clip clip = clipHandler.getDefault(); <-- ***** throws an NPE *****

春天WebInitilizer

public class SpringWebInitialiser implements WebApplicationInitializer {

  @Override
  public void onStartup(ServletContext container) {

    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(RootConfig.class);
    rootContext.setServletContext(container);
    container.addListener(new ContextLoaderListener(rootContext));

    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(WebConfig.class);

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
  }
}

还有 bean 配置(注意我也尝试将 bean 添加到 RootConfig

@Configuration
@ComponentScan ({ ... })
public class WebConfig {

  @Bean
  public ClipHandler clipHandler() {
    return new ClipHandler();
  }
}

【问题讨论】:

    标签: java spring jersey jax-rs spring-4


    【解决方案1】:

    您可以在球衣资源中手动调用自动装配,如下所示:

    @Context
    private ServletContext servletContext;
    
    @PostConstruct
    public void init() {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, servletContext);
    }
    

    【讨论】:

    • 如果我删除 @Component 那么它就可以了。我见过据称不需要删除它的例子。任何想法如何做到这一点?
    • 似乎替代用户 jersey-spring3 从纯粹主义者的角度来看,这对于 spring4 应用程序来说并不理想。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多