我創建了一個類來管理髮送郵件,我想通過屬性文件注入smtp配置。但我一直在我的領域屬性爲空。 這是我的代碼:@Inject屬性在Tomcat上返回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";
}
我測試的代碼用一個簡單的主力,但它不工作。 我用tomcat測試了它,並且仍然在Properties對象上獲得了NPE。 我錯過了什麼? 請幫助:)
您的兩個類都是託管的bean嗎?注入和生產者只能在受管理的環境中工作。 –
嗨Dimpre,我應該註釋他們嗎?我讀過的教程沒有註釋。 – Khairy
Tomcat與EE技術的正式發佈,TomEE,存在幾個版本。非常好,並且與'classic'Tomcat兼容 –