Dropwizard中配置依赖注入(Guice)

一、Maven配置


  ru.vyarus
  dropwizard-guicey
  7.0.0

二、注册guice包

public class HorseApplication extends Application {

    public static void main(final String[] args) throws Exception {
        new HorseApplication().run(args);
    }

    @Override
    public String getName() {
        return "Horse";
    }

    @Override
    public void initialize(final Bootstrap bootstrap) {
        // 注册guice包
        GuiceBundle guiceBundle = GuiceBundle.builder()
                .enableAutoConfig()
                .build();
        bootstrap.addBundle(guiceBundle);
    }

    @Override
    public void run(final HorseConfiguration configuration,
                    final Environment environment) {
    }
}

三、依赖注入(三种方式)

(1)构造器注入

@Path("/goods")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class GoodsResource {

    private final GoodsRepository goodsRepository;

    @Inject
    public GoodsResource(GoodsRepository goodsRepository) {
        this.goodsRepository = goodsRepository;
    }
}

(2)字段注入

@Path("/goods")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class GoodsResource {

    @Inject
    private GoodsRepository goodsRepository;
}

(3)Setter方法注入

@Path("/goods")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class GoodsResource {
    
    private GoodsRepository goodsRepository;

    @Inject
    public void setGoodsRepository(GoodsRepository goodsRepository) {
        this.goodsRepository = goodsRepository;
    }
}

你可能感兴趣的:(Dropwizard,java,restful,后端)