【发布时间】:2017-09-09 05:59:00
【问题描述】:
我创建了一个类来管理发送电子邮件,我想通过属性文件注入 smtp 配置。但是我的字段属性一直为空。 这是我的代码:
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。 我错过了什么? 请帮忙:)
【问题讨论】:
-
你的两个类都是托管 bean 吗?注入和生产者仅在托管上下文中工作。
-
嗨 Dimpre,我应该注释它们吗?我阅读的教程没有注释。
-
Tomcat 有 EE 技术的官方发行版,TomEE,很少有版本存在。非常好,与“经典”Tomcat 兼容
标签: tomcat jakarta-ee cdi