私は基本的に、ローカルインターフェースを持つ @Stateless Bean を @Named で注釈が付けられたクラスに注入しようとしています! 私の理解では、注入ポイントが管理されている場合にのみ注入が可能です (完全に理にかなっています)。たとえば、POJO に注入することはできませんが、サーブレット、JSF 管理、または別の EJB に注入することはできます。
@Named! ただし、実際にはこれが可能ではないように思われる NullPointerException が発生します!?
私のクラスは次のようになります (わかりやすくするために省略しています)。
@Named
public class EmailUtil {
// Logger-------------------------------------------------------------------
private static final Logger LOG = Logger.getLogger(EmailUtil.class.getName());
// Constructor--------------------------------------------------------------
public EmailUtil() {
}
// EJB----------------------------------------------------------------------
@EJB AuditDAO audit;
// Methods------------------------------------------------------------------
public void sendEmail(
String emailSender,
String emailRecipient,
String emailSubject,
String emailHtmlBody,
String emailTextBody) throws FailedEmailException {
... code removed for clarity ...
// Call Amazon SES to send the message
try {
new SES().getClient().sendEmail(request);
// Create an audit log of the event
audit.create("Email sent to " + emailSender);
} catch (AmazonClientException ace) {
LOG.log(Level.SEVERE, ace.getMessage(), ace);
throw new FailedEmailException();
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
}
}
}
@Stateless
public class AuditDAOImpl implements AuditDAO {
// Logger-------------------------------------------------------------------
private static final Logger LOG = Logger.getLogger(AuditDAOImpl.class.getName());
// EntityManager------------------------------------------------------------
@PersistenceContext(unitName = "iConsultPU")
private EntityManager em;
@Override
public void create(String event) {
String subject;
try {
/*
* If the current subject has authenticated and created a session we
* want to register their ID. However it is possible that a subject
* does not have an ID so we want to set it to unknown.
*/
subject = SecurityUtils
.getSubject()
.getPrincipals()
.asList()
.get(1)
.toString();
} catch (Exception e) {
subject = "UNKNOWN";
}
Audit audit = new Audit();
audit.setUserId(subject);
audit.setEventTime(Calendar.getInstance());
audit.setEvent(event);
em.persist(audit);
}
}
@Local
public interface AuditDAO {
public void create(String event);
}
@Inject も使用してみましたが、それもうまくいかないようです。仕様を誤解したのか、実装が不十分だったのか?