ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java-将@Resource注入普通类

2019-10-23 18:03:17  阅读:748  来源: 互联网

标签:code-injection glassfish java java-ee


我使用的是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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有