如何将spring对象注入cordaApp项目?

时间:2018-01-19 11:28:49

标签: corda

我创建了一个小型弹簧库,我想将它集成到CorDapp项目中。

我在CorDapp构建gradle中添加了所有必需的spring依赖项,但是当我运行Application时,我的@Autowired类变为null。

任何人都可以在这方面提供帮助,或者之前有人尝试过这种功能吗?

总之我想将spring对象注入cordaApp项目,是否可能?

<<<<<<<<<<以下是代码示例>>>>>>>>>>>>>>>>

ExampleApi类包含“metoo”REST API,并使用@Component注释,TestComp@Autowired

@Path("example")
@Component
public class ExampleApi {
    private final CordaRPCOps rpcOps;
    private final CordaX500Name myLegalName;

    public ExampleApi(CordaRPCOps rpcOps) {
        this.rpcOps = rpcOps;
        this.myLegalName = rpcOps.nodeInfo().getLegalIdentities().get(0).getName();
    }

    @Autowired
    TestComp testComp;

    @GET
    @Path("metoo")
    @Produces(MediaType.APPLICATION_JSON)
    public String whoamitest() {
        // here testComp is getting null at runtime
        return testComp.getMyName();
    }
}

=============================================== ====================

示例TestComp类如下所示:

@Component
public class TestComp {

    public String getMyName()  {
        return "Hello there ...";
    }
}

=============================================== ====================

在com.example包中添加了Application类,如下所示

添加了JerseyConfig类,如下所述:

@Configuration
@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        packages("com.example");
        register(ExampleApi.class);
    }

    @Bean
    public ServletRegistrationBean jerseyServlet() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/*");
        // our rest resources will be available in the path /rest/*
        registration.addInitParameter(
        ServletProperties.JAXRS_APPLICATION_CLASS, 
        JerseyConfig.class.getName());
        return registration;
    }
}

=============================================== =============

在build.gradle文件中添加了以下库/依赖项:

compile (group: 'org.springframework.boot', name: 'spring-boot-starter-jersey', version: '1.5.9.RELEASE'){
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

compile(group: 'org.springframework.boot',name: 'spring-boot-starter-web' , version: '1.5.9.RELEASE') {
    exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}

compile group: 'org.springframework.boot', name: 'spring-boot-configuration-processor', version: '1.5.9.RELEASE'

=============================================== ==================

将以下内容添加到外部build.gradle文件中:

classpath group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '1.5.9.RELEASE', ext: 'pom'

=============================================== ===================

1 个答案:

答案 0 :(得分:2)

这种结构根本无法运作:

  • 一方面,您要定义ExampleApi并将其列在CorDapp的网络插件注册表中。这意味着API将在编译时获取并转换为默认节点webserver的一组端点,这是一个Jetty webserver

  • 另一方面,您正在定义一个独立的Spring网络服务器

这两个Web服务器作为完全独立的Java进程运行,因此无法在另一个中注入Autowired个类。