我使用的是 glassfish v3,我通过管理控制台创建了一个 JavaMail session 。我想像这样使用邮件 session :
....
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.*;
public class Mailer {
MailGenerator mailGenerator;
@Resource(name = "mail/WMCMail")
private Session mailSession;
public Mailer(MailGenerator mailGenerator) {
this.mailGenerator = mailGenerator;
}
public void sendMixedMail(String recipient, String subject) {
try {
Message message = new MimeMessage(mailSession);
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(recipient, false));
message.setSubject(subject);
......
Transport.send(message);
logger.log(Level.INFO, "Mail sent to {0}.", recipient);
} catch (MessagingException ex) {
logger.log(Level.SEVERE, "Error in sending email to " + recipient, ex);
}
}
}
当我调用 sendMixedMail 方法时,我发现 mailSession 为空。不能将资源注入(inject)普通类吗?当我说正常时,我指的是一个不是托管 bean 或 ejb 之类的类。
最佳答案
不,您不能为普通类(class)这样做。引自 SUN's J2EE injection page :
Keep in mind that a Java EE 5 platform container can handle the injections transparently only when they are used on container-managed components, such as EJB beans, Servlets, and JavaServer Pages (JSP) technology tag handlers.
This is for two reasons. First, for performance considerations, a container can restrict its search of annotations only to the components it manages, which are defined in a deployment descriptor or are accessible in specific classpath locations. Second, the container must have control over the creation of the component to be able to transparently perform the injection into the component.
关于java - 将@Resource注入(inject)普通类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4387857/