编程语言
首页 > 编程语言> > java-将@Resource注入普通类

java-将@Resource注入普通类

作者:互联网

我使用的是glassfish v3,我在其中通过管理控制台创建了JavaMail会话.我想这样使用Mail会话:

....
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为null.是否不可能将Resource注入普通类?当我说正常时,我的意思是不是托管bean或ejb之类的类.

解决方法:

不,您不能在普通班上那样做.从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.

标签:code-injection,glassfish,java,java-ee
来源: https://codeday.me/bug/20191023/1914699.html