注入返回String CDI的生产者方法 [英] Inject producer method that returns String CDI

查看:181
本文介绍了注入返回String CDI的生产者方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用CDI向JSF Web应用程序中的托管bean注入常量字符串消息,这里是生产者类:

I would like to inject constant string message to managed bean in JSF web application using CDI, here is producer class:

@Named
@RequestScoped
public class StringProducer {

   @Produces
   @Named("message")    
   @RequestScoped
   public String getMessage() {
      return "Hello World";
   }
}

以下是它在另一个托管bean中的注入方式:

and here is how it is injected in another managed bean:

@Inject Named("message") String message;

但这总是导致异常:

org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001435 Normal scoped bean int is not proxyable

我试图在Instance中包装String类型,如下所示:

I tried to wrap String type within Instance like this:

@Inject Named("message") Instance<String> message;

但没有任何改变。

推荐答案

问题是您在producer方法上使用 @RequestScoped 注释。删除它,应用程序将按预期工作。

The problem is your use of the @RequestScoped annotation on the producer method. Remove it and the application will work as expected.

Request Scoped 注释用于注释容器管理的 Beans 。为此,容器代理对象的公共方法。但是像String这样的最终类是不可代理的,正如使用Weld 2.0.0 SP1在Glassfish 4.0上运行代码时的异常所指出的那样:

The Request Scoped annotation is used to annotate Beans managed by the container. To do so, the container proxies the object's public methods. Final classes like String are however not proxyable, as pointed out by the exception when running the code on Glassfish 4.0 with Weld 2.0.0 SP1:

WELD-001437 Normal scoped bean class java.lang.String is not proxyable because the type is final or it contains a final method class java.lang.String - Producer Method [String] (...etc.)

这篇关于注入返回String CDI的生产者方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆