Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我在资源中注入了服务接口,但无法确定如何配置资源方法调用_Java_Guice_Dropwizard_Inject - Fatal编程技术网

Java 我在资源中注入了服务接口,但无法确定如何配置资源方法调用

Java 我在资源中注入了服务接口,但无法确定如何配置资源方法调用,java,guice,dropwizard,inject,Java,Guice,Dropwizard,Inject,这是我为启动资源而编写的代码。无法注册资源类。使用Mongo数据库和@Injected的基础知识 @JsonIgnoreProperties(ignoreUnknown = true) public class Student extends BaseModel { private String firstName; private String lastName; private String marks; private long dob; @Ema

这是我为启动资源而编写的代码。无法注册资源类。使用Mongo数据库和@Injected的基础知识

@JsonIgnoreProperties(ignoreUnknown = true)
public class Student extends BaseModel {

    private String firstName;
    private String lastName;
    private String marks;
    private long dob;
    @Email
    private String email;


    public Student() {
    }

    public Student(String firstName, String lastName, String marks, long dob, @Email String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.marks = marks;
        this.dob = dob;
        this.email = email;
    }
//Getter Setter method 
}

//Base Repository Interface
public interface BaseRepository<T extends BaseModel> extends GenericRepository<T> {

    T save (T model);
    List<T> getAll();
    T getById(String Id);
    void deleteById(String Id);
    T updateById(String Id, T model);
}

在上面的示例中,您将资源声明为HK托管:

@hkmanaged
@定时
公共班级学生资源{
这意味着HK2(jersey的DI)将实例化对象而不是guice

但您的服务是在guice模块中声明的:

公共类应用程序连接器扩展了AbstractModule/*AbstractBinder*/{
私有最终配置上下文;
公共应用程序连接器(配置上下文){
this.context=上下文;
}
@施工后
@凌驾
受保护的void configure(){
绑定(StudentService.class).to(studentserviceinpl.class);
绑定(StudentRepository.class).to(StudentRepositoryImpl.class);
}
因此,您的服务不能注入
StudentService
是正常的,因为HK2不知道guice依赖关系

这可以通过修复,以便HK可以使用GUI绑定:

  • 添加依赖项:org.glassfish.hk2:guice-bridge:2.5.0-b32(版本必须与dropwizard使用的hk2版本匹配)
  • 启用选项:。选项(GuiceyOptions.UseHkBridge,true)

在github项目()中,您有一个相反的情况:

资源由guice管理(guice创建资源实例)

@Path(“/student”)
@产生(MediaType.APPLICATION_JSON)
@使用(MediaType.APPLICATION_JSON)
@定时
公共班级学生资源{
服务在香港声明:

公共类应用程序连接器扩展/*AbstractModule*/AbstractBinder{
@施工后
@凌驾
受保护的void configure(){
绑定(StudentService.class).to(studentserviceinpl.class);
绑定(StudentRepository.class).to(StudentRepositoryImpl.class);
}
}
(但该模块实际上从未注册)


我的建议是在guice环境中“生存”:不要使用
@HKManaged
(它只针对边缘案例添加)并使用guice模块进行服务声明。这样guice将负责与您的代码相关的所有DI。

JAX-WS不是Dropwizard的一部分,它的支持由提供。您似乎使用了此扩展,对吗?如果取消注释行
jaxWsBundle.publishEndpoint(new EndpointBuilder(“学生”)会发生什么,new StudentResource());
?com.roskart.dropwizard.jaxws.JAXWSEnvironment.publishEndpoint(JAXWSEnvironment.java:135)在com.roskart.dropwizard.jaxws.JAXWSBundle.publishEndpoint(JAXWSBundle.java:85)在App.run(App.java:97)在io.dropwizard.cli.EnvironmentCommand.run(EnvironmentCommand.java:43)在App.run在io.dropwizard.cli.ConfiguredCommand.run(ConfiguredCommand.java:87)在io.dropwizard.cli.cli.run(cli.java:78)在io.dropwizard.Application.run(Application.java:93)在App.main(App.java:42)在App.main(App.java:42)请回答您的问题,包括您使用的实际代码和错误。这是一个我无法找出实际错误的项目
 public BaseRepositoryImpl(MongoDb mongoManager, Class<T> clazz) throws Exception{
        this.mongoManager = mongoManager;
        collectionName = clazz.getAnnotation(CollectionName.class);
        collection = mongoManager.getMongoCollection(collectionName.name());
        entityClass = clazz;
    }

    @Override
    public T save(T model) {
        if(model == null){
            throw new RuntimeException("No data Found");
        }
        Object id = collection.save(model).getUpsertedId();
        if(id != null && id instanceof ObjectId){
            model.setId(((ObjectId) id).toStringMongod());
        }
        return model;
    }
}

//service
public interface StudentService {
    Student save(Student student);
}


//Resource 
WebService
@Path("/student")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@HK2Managed
@Timed
public class StudentResource {


    @Inject
    StudentService studentService;

   /* @Inject
    public StudentResource(StudentService studentService) {
        this.studentService = studentService;
    }*/

    @Path("/getName")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getName(){
        return "Puru";
    }
}
    private String template;
    // private StudentService studentService;

    private String defaultName = "Stranger";

    public MongoConfiguration getMongoConfiguration() {
        return mongoConfiguration;
    }

    public void setMongoConfiguration(MongoConfiguration mongoConfiguration) {
        this.mongoConfiguration = mongoConfiguration;
    }


    @Valid
    @JsonProperty("mongoserver")
    public MongoConfiguration mongoConfiguration;
}

//Application Connector  to bind the Class in interface of the Respected Class 

public class ApplicationConnector extends AbstractModule /*AbstractBinder*/ {

    private final ConfigurationContext context;

    public ApplicationConnector(ConfigurationContext context) {
        this.context = context;
    }

    @PostConstruct
    @Override
    protected void configure() {
        bind(StudentService.class).to(StudentServiceImpl.class);
        bind(StudentRepository.class).to(StudentRepositoryImpl.class);
    }

// applicaytion Connector Class 

public class App extends Application<AppConfiguration> {

    GuiceBundle<AppConfiguration> guiceBundle = null;
    private JAXWSBundle jaxwsBundle = new JAXWSBundle();
    public static void main(final String[] args) throws Exception {
        new App().run(args);
    }
    private JAXWSBundle<Object> jaxWsBundle = new JAXWSBundle<>("/api");
    @Override
    public String getName() {
        return "student-DropWizard-demo";
    }

    @Override
    public void initialize(final Bootstrap<AppConfiguration> bootstrap) {
        // TODO: application initializatio
//        bootstrap.getObjectMapper().enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
//        bootstrap.addBundle(GuiceBundle.<AppConfiguration>builder()
//                .enableAutoConfig("package.to.scan")
//                .searchCommands(true)
//                .build()
//        );
             /*  GuiceBundle.Builder builder = GuiceBundle.builder() .noDefaultInstallers()
                .enableAutoConfig("com.dzone");
               guiceBundle = builder.build();*/
//        bootstrap.addBundle(GuiceBundle.builder().enableAutoConfig("com.dzone")
//                .build());

      //  Module[] modules = autoDiscoverModules();


        bootstrap.getObjectMapper().registerSubtypes(DefaultServerFactory.class);
//bootstrap.getObjectMapper().registerModule(new FCSerializerModule());
        bootstrap.getObjectMapper().enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        bootstrap.addBundle(jaxwsBundle);
        GuiceBundle.Builder builder = GuiceBundle.builder()
//                .modules(modules)
                .noDefaultInstallers()
                .installers(new Class[]{LifeCycleInstaller.class,
                        ManagedInstaller.class,
                        JerseyFeatureInstaller.class, ResourceInstaller.class,
                        JerseyProviderInstaller.class,
                        EagerSingletonInstaller.class,
                        HealthCheckInstaller.class,
                        TaskInstaller.class,
                        PluginInstaller.class
                })
                .enableAutoConfig(ApplicationConnector.class.getPackage().getName());
        postInitialize(bootstrap, builder);
        guiceBundle = builder.build();
        bootstrap.addBundle(guiceBundle);
    }

    @Override
    public void run(final AppConfiguration configuration,
                    final Environment environment) throws Exception {
        // TODO: implement application
      //  FilterRegistration.Dynamic dFilter = environment.servlets().addFilter("student", CrossOriginFilter.class);
//   AbstractServerFactory sf = (AbstractServerFactory) configuration.getServerFactory();

//        Endpoint e =  jaxWsBundle.publishEndpoint(
//                new EndpointBuilder("student", new StudentResource()));
       // environment.jersey().register(new StudentResource());
        //environment.jersey().register(new StudentServiceImpl());
        //environment.jersey().packages("service");
      //  environment.jersey().disable();
       // environment.servlets().addServlet(StudentResource.class).addMapping("/student");
        environment.getJerseyServletContainer().getServletInfo();
        //environment.servlets().setBaseResource("");
        ///environment.servlets().addServlet("StudentResource",StudentResource.class);
       //environment.jersey().register(new ResourceInstaller());

        postRun(configuration,environment);
    }

    protected void postRun(final AppConfiguration configuration, final Environment environment) throws Exception {
        // Sub-classes should
    }

    protected void postInitialize(Bootstrap<AppConfiguration> bootstrapm, GuiceBundle.Builder guiceBuilder) {
        // Sub-classes should
    }
 /*public Module[] autoDiscoverModules() {
        Reflections reflections =
                new Reflections(
                        new ConfigurationBuilder()
                                .forPackages(
                                       "com.dzone"));

        Set<Class<? extends AbstractModule>> classes = reflections.getSubTypesOf(AbstractModule.class);

        List<Module> discoveredModules = new ArrayList<>();
        for (Class clazz : classes) {
            try {
                AbstractModule module = (AbstractModule) clazz.newInstance();
                discoveredModules.add(module);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return discoveredModules.toArray(new Module[]{});
    }
}
WARN  [2019-09-09 05:32:31,707] io.dropwizard.setup.AdminEnvironment: 
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!    THIS APPLICATION HAS NO HEALTHCHECKS. THIS MEANS YOU WILL NEVER KNOW      !
!     IF IT DIES IN PRODUCTION, WHICH MEANS YOU WILL NEVER KNOW IF YOU'RE      !
!    LETTING YOUR USERS DOWN. YOU SHOULD ADD A HEALTHCHECK FOR EACH OF YOUR    !
!         APPLICATION'S DEPENDENCIES WHICH FULLY (BUT LIGHTLY) TESTS IT.       !
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
INFO  [2019-09-09 05:32:31,711] org.eclipse.jetty.server.handler.ContextHandler: Started i.d.j.MutableServletContextHandler@615db358{/,null,AVAILABLE}
INFO  [2019-09-09 05:32:31,718] org.eclipse.jetty.server.AbstractConnector: Started application@f9cab00{HTTP/1.1,[http/1.1]}{0.0.0.0:8099}
INFO  [2019-09-09 05:32:31,719] org.eclipse.jetty.server.AbstractConnector: Started admin@10272bbb{HTTP/1.1,[http/1.1]}{0.0.0.0:8091}
INFO  [2019-09-09 05:32:31,719] org.eclipse.jetty.server.Server: Started @5573ms
INFO  [2019-09-09 05:32:31,719] com.roskart.dropwizard.jaxws.JAXWSEnvironment: No JAX-WS service endpoints were registered.