我有一個簡單的AttributeConverter
實現,其中我嘗試注入一個必須提供轉換邏輯的對象,但@Inject
似乎不適用於這種情況。該轉換器類看起來是這樣的:@Inject在AttributeConverter中不工作
@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工作,豆必須符合這裏描述的條件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。所以問題還沒有解決。
也許是以下的副本:http://stackoverflow.com/questions/12080317/inject-only-working-for-pojos-created-by-cdi-container – MWiesner
部分它是重複的,但是有一個特定的Spring提供的解決方案不適用於我,因爲我沒有使用Spring。我用一些新的經驗擴展了我的案例的描述,但問題仍未解決。 – Svetoslav