此内容没有您所选择的语言版本。

Chapter 5. Using Quarkus dependency injection


Dependency injection enables a service to be used in a way that is completely independent of any client consumption. It separates the creation of client dependencies from the client’s behavior, which enables program designs to be loosely coupled.

Dependency injection in Red Hat build of Quarkus is based on Quarkus ArC which is a CDI-based build-time oriented dependency injection solution tailored for Quarkus architecture. Because ArC is a transitive dependency of quarkus-resteasy, and quarkus-resteasy is a dependency of your project, ArC will already be downloaded.

Prerequisites

  • You have created the Quarkus Getting Started project.

Procedure

  1. To modify the application and add a companion bean, create the src/main/java/org/acme/quickstart/GreetingService.java file with the following content:

    package org.acme.quickstart;
    
    import javax.enterprise.context.ApplicationScoped;
    
    @ApplicationScoped
    public class GreetingService {
    
        public String greeting(String name) {
            return "hello " + name;
        }
    
    }
  2. Edit the src/main/java/org/acme/quickstart/GreetingResource.java to inject the GreetingService and create a new endpoint using it:

    package org.acme.quickstart;
    
    import javax.inject.Inject;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    
    import org.jboss.resteasy.annotations.jaxrs.PathParam;
    
    @Path("/hello")
    public class GreetingResource {
    
        @Inject
        GreetingService service;
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        @Path("/greeting/{name}")
        public String greeting(@PathParam String name) {
            return service.greeting(name);
        }
    
        @GET
        @Produces(MediaType.TEXT_PLAIN)
        public String hello() {
            return "hello";
        }
    }
  3. If you stopped the application, enter the following command to restart it:

    ./mvnw compile quarkus:dev
  4. To verify that the endpoint returns hello quarkus, enter the following command in a new terminal window:

    curl -w "\n" http://localhost:8080/hello/greeting/quarkus
    hello quarkus
Red Hat logoGithubRedditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

© 2024 Red Hat, Inc.