简体   繁体   English

如何再次注入产品

[英]How to Inject produces again

Using javaee beans, is there possibility to inject properties again if they are, for example, null?使用 javaee bean,是否有可能再次注入属性,例如 null?

My simplified code:我的简化代码:

Service makes rest request to another service, and it get host property from a PropertyProduces that takes it from a third config service.服务另一个服务发出 rest 请求,并从PropertyProduces获取主机属性,该属性从第三个配置服务获取。 For example, when I first time making RestService.call() , config service is disabled, so it return host=null.例如,当我第一次制作RestService.call()时,配置服务被禁用,所以它返回 host=null。 I am not able to callAnotherService properly, this is fine.我无法正确调用AnotherService ,这很好。 Then config service became enabled, but when I make second RestService.call() , host is already null and it even do not want to get to PropertyProduces.produceString然后启用了配置服务,但是当我创建第二个RestService.call()时,主机已经是 null 它甚至不想访问PropertyProduces.produceString

Can I somehow intercept usage of host property, check if it is null and force it to inject from Produces again?我可以以某种方式拦截主机属性的使用,检查它是否是 null 并强制它再次从 Produces 注入?

@ApplicationScoped
public class Service {
    @Property
    private final String host;

    public void callAnotherService() {
        callRestMethod(host)
    }
}
@ApplicationScoped
public class PropertyProduces {

    @Inject
    private Config config;

    @Property
    @Produces
    public String produceString(InjectionPoint ip) {
        return this.config.getString(ip.getMember().getName());
    }
}
@Path("/")
@ApplicationScoped
public class RestService {
    @Inject
    private Service service;
  
    @POST
    @Path("/call")
    public Response call(Request request)
    {
        this.service.callAnotherService();
    }
}

I know I can change class Service to @RequestScoped, so at different rest requests will be created different Service instances and host will be produces everytime.我知道我可以将 class服务更改为 @RequestScoped,因此在不同的 rest 请求将创建不同的服务实例,并且每次都会生成主机。 But is there another posibility, somehow changing PropertyProduces or making Interceptors?但是否还有另一种可能性,以某种方式改变 PropertyProduces 或制作拦截器?

You should try to use dynamic bean selection on your Service class:您应该尝试在您的服务 class 上使用动态 bean 选择:

 @Inject
 @Property
 Instance<String> instance;

and then in your Service method you can do:然后在您的 Service 方法中,您可以执行以下操作:

public void callAnotherService() {
     String host = instance.get();
     callRestMethod(host)
}

More references at https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/Instance.html更多参考https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/Instance.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM