【发布时间】:2015-10-11 12:58:21
【问题描述】:
我有一个简单的AttributeConverter 实现,我尝试注入一个必须提供转换逻辑的对象,但@Inject 似乎不适用于这种情况。转换器类如下所示:
@Converter(autoApply=false)
public class String2ByteArrayConverter implements AttributeConverter<String, byte[]>
{
@Inject
private Crypto crypto;
@Override
public byte[] convertToDatabaseColumn(String usrReadable)
{
return crypto.pg_encrypt(usrReadable);
}
@Override
public String convertToEntityAttribute(byte[] dbType)
{
return crypto.pg_decrypt(dbType);
}
}
当@Converter 被触发时,它会抛出一个NullPointerException,因为属性crypto 没有从容器中初始化。这是为什么?
我使用的是 Glassfish 4,在所有其他情况下 @Inject 工作正常。
不能在转换器上使用 CDI 吗?
任何帮助将不胜感激:)
我的问题的重点更多是 AttributeConverter 部分。我知道要使 CDI 工作,bean 必须满足http://docs.oracle.com/javaee/6/tutorial/doc/gjfzi.html 此处描述的条件。 我还尝试通过实现以下构造函数来强制 CDI 工作:
@Inject
public String2ByteArrayConverter(Crypto crypto)
{
this.crypto = crypto;
}
现在我得到了以下异常,它没有给我任何线索:
2015-07-23T01:03:24.835+0200|Severe: Exception during life cycle processing
org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [PU_VMA] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-7172] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when instantiating the class [class model.converter.String2ByteArrayConverter].
Internal Exception: java.lang.InstantiationException: model.converter.String2ByteArrayConverter
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:820)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:760)
...
我什至尝试使用@Producer 或@Decorator 来让CDI 在那个地方工作,但我仍然认为AttributeConverter 有一些特定的东西不允许CDI。所以问题还没有解决。
【问题讨论】:
-
可能与以下内容重复:stackoverflow.com/questions/12080317/…
-
部分是重复的,但是提供了一个特定于 Spring 的解决方案,它对我不起作用,因为我没有使用 Spring。我用一些新的经验扩展了我的案例描述,但问题仍然没有解决。
标签: jpa glassfish converter cdi