开发者

Inject @Resource into normal class

I am using glassfish v3 where I created a JavaMail session through the admin console开发者_如何学Python. I want to use the Mail session like this:

....
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);
        } 
    }
}

When I call the sendMixedMail method I see that the mailSession is null. Is it not possible to inject a Resource into a normal class? And when I say normal I mean a class which is not a managed bean or a ejb-something.


No, you cannot do that for a normal class. Quoting from 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜