@Inject属性在Tomcat上返回null

时间:2017-09-09 05:59:00

标签: tomcat java-ee cdi

我创建了一个用于管理发送电子邮件的类,我想通过属性文件注入smtp配置。但是我的字段属性保持为null。 这是我的代码:

public class EmailUtils { 
    @Inject
    @PropertiesFromFile("smtp.properties")
    Properties properties;

    public void sendEmail(String destinator, String subject, String body) {
        final String username = properties.getProperty("smtp.email");
        final String password = properties.getProperty("smtp.password");

        Session session = Session.getInstance(properties,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(properties.getProperty("smtp.from")));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(destinator));
            message.setSubject(subject);
            message.setText(body);

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
   }
}

public class PropertyReader {

    @Produces
    @PropertiesFromFile
    public Properties provideServerProperties(InjectionPoint ip) {
    //get filename from annotation
    String filename = ip.getAnnotated().getAnnotation(PropertiesFromFile.class).value();
    return readProperties(filename);
}

    private Properties readProperties(String fileInClasspath) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileInClasspath);

        try {
            Properties properties = new Properties();
            properties.load(is);
            return properties;
       } catch (IOException e) {
           System.err.println("Could not read properties from file " + fileInClasspath + " in classpath. " + e);
       } catch (Exception e) {
           System.err.println("Exception catched:"+ e.getMessage());
       } 

       return null;
   }
}

@Qualifier
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface PropertiesFromFile {
    @Nonbinding
    String value() default "application.properties";
}

我用简单的Main测试了代码,但它不起作用。 我用tomcat测试了它,并且仍然在Properties对象上获得了NPE。 我错过了什么? 请帮助:)

2 个答案:

答案 0 :(得分:3)

请考虑使用此Java EE方式:

  1. 如果使用Tomcat,请确保使用How to install and use CDI on Tomcat?Application servers and environments supported by Weld中所述的CDI实施进行设置。

  2. 将JavaMail实现jar从您的应用程序的WEB-INF/lib移动到Tomcat lib目录。

  3. 通过在Tomcat的config/Context.xml文件中添加以下内容,在Tomcat中配置您的电子邮件会话:

    <Context>
        ...
        <Resource name="mail/Session" auth="Container"
          type="javax.mail.Session"
          mail.smtp.host="your mail host here"
          mail.smtp.user="your user name here"
          password="your password"
          mail.from="noreply@yourdomain.com" />
        ...
    </Context>   
    

    还有其他地方可以使用此配置,但这是最简单的解释。有关详细信息,请参阅Tomcat JNDI documentation

  4. 简化您的代码:

        @Resource(name="mail/Session")
        private Session session;
    
        public void sendEmail(String destinator, String subject, String body) {
            try {
    
                Message message = new MimeMessage(session);
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(destinator));
                message.setSubject(subject);
                message.setText(body);
    
                Transport.send(message);
    
                System.out.println("Done");
    
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
    

    您的服务器(本例中为Tomcat)负责为您配置邮件会话和身份验证。

  5. 类似的机制适用于设置JDBC DataSource对象FWIW。

答案 1 :(得分:2)

使用PropertyReader@Named为您的@ApplicationScoped课程添加注释,以使其知道CDI容器,以便对其进行管理。在课程路径中留空beans.xml