加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

rest – 如何使用Jersey将依赖项注入资源?

发布时间:2020-12-13 20:12:10 所属栏目:百科 来源:网络整理
导读:我有以下代码: @Path("stores")class StoreResources { private ServerConfig config; @GET public String getAll() { //do some stuff with ServerConfig }} 我需要从外部将ServerConfig对象注入到此类中,并在getAll()方法中使用它. 有哪些可能的方法来实
我有以下代码:
@Path("stores")
class StoreResources {

  private ServerConfig config;

  @GET
  public String getAll() {
   //do some stuff with ServerConfig
  }
}

我需要从外部将ServerConfig对象注入到此类中,并在getAll()方法中使用它.

有哪些可能的方法来实现它?我应该使用像Guice或Spring这样的DI框架吗?

这是关于Jersey http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html下Spring注入的好博客

结果是你使用注释来标记要注入的字段,这是一个示例资源

package com.km.services;  

import javax.ws.rs.GET;  
import javax.ws.rs.Path;  
import javax.ws.rs.Produces;  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Component;  
import com.sun.jersey.spi.inject.Inject;  
import com.km.spring.SimpleBean;  

@Path("/hello")  
@Component  
@Scope("request")  
public class HelloResource {  

   @Inject private SimpleBean simpleBean;  

   @GET  
   @Produces("text/plain")  
   public String getMessage() {  
    return simpleBean.sayHello();  
   }  
}

为了我的目的,配置过于困难所以我使用静态弹簧解析器工厂来解析bean.例如.

private SimpleBean simpleBean = SpringBeanFactory.getBean("mySimpleBean");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读