gpt4 book ai didi

java - @Value 不从 application.properties 注入(inject)数据

转载 作者:行者123 更新时间:2023-12-02 01:59:19 42 4
gpt4 key购买 nike

我将向您展示一些代码,然后我会问一个问题。

SendEmail.java

package com.goode;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

@Component
@NoArgsConstructor
@Data
@AllArgsConstructor
public class SendEmail {

@Value("${email.username}")
private String username;

@Value("${email.password}")
private String password;

@Value("${email.fullAddress}")
private String fullAddress;

@Value("${email.host}")
private String host;

@Value("${email.port}")
private String port;

public boolean send(String toEmail, String subject, String message){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);

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

try {
Message createMessage = new MimeMessage(session);
createMessage.setFrom(new InternetAddress(fullAddress));
createMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
createMessage.setSubject(subject);
createMessage.setText(message);
Transport.send(createMessage);

return true;

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

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
{
PropertySourcesPlaceholderConfigurer o = new PropertySourcesPlaceholderConfigurer();
o.setLocation(new ClassPathResource("application.properties"));
return o;
}
}

RootConfig.java

package com.goode.config;

import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableJpaRepositories( basePackages = {"com.goode.repository"})
@PropertySource(value = { "classpath:application.properties" })
@EnableTransactionManagement
@Import({ SecurityConfig.class })
@ComponentScan(basePackages = {"com.goode.service", "com.goode.repository", "com.goode.controller", "com.goode.business", "com.goode"})
public class RootConfig {

@Autowired
private Environment environment;

@Autowired
private DataSource dataSource;

@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));

return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.POSTGRESQL);
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);

LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.goode.business");
factory.setDataSource(dataSource());
factory.setJpaProperties(jpaProperties());

return factory;
}

private Properties jpaProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
@Bean
public PlatformTransactionManager transactionManager() {

JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory().getObject());
return txManager;
}

}

application.properties

jdbc.driverClassName = org.postgresql.Driver
jdbc.url = jdbc:postgresql://localhost:5432/GoodE
jdbc.username = postgres
jdbc.password = postgres
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
email.username = xx //I replce real data to xx just to this post
email.password = xx
email.fullAddress = xx@xx.com
email.host = xx
email.port = xx

当我尝试从 SendEmail 控制台调用 send 方法时显示错误:

java.lang.NullPointerException: null

行内:

props.put("mail.smtp.host", host);

因此注释 @Value 不会将 application.properties 中的任何值注入(inject)到 SendEmail 中的私有(private)变量中。这是为什么?

RootConfig.java中,我使用了@AutowiredEnvironment@PropertySource,但我在某处读到您只能在 @Configuration 类中使用 @PropertySource,所以我尝试寻找另一种方法 -> 我找到了 @Value,但我不知道为什么 application.properties 中的数据没有注入(inject)到变量中。我将 PropertySourcesPlaceholderConfigurer 放入 SendEmail 中,因为我认为这是必要的。我不确定这是放置它的正确位置,但将其放在另一个类中,例如RootConfig 没有帮助。您有什么建议我应该在哪里搜索错误吗?

最佳答案

这一行:@PropertySource(value = { "classpath:application.properties"})是不必要的,因为默认情况下会选取 application.properties 中的所有值。话虽这么说,您也不需要 PropertySourcesPlaceholderConfigurer

确保在调用 send 方法时,您没有将 SendEmail 类实例化为 new SendEmail(),因为这不会作为 @Value 工作仅在 Spring 应用程序上下文内部工作。

您必须执行@Autowired或构造函数注入(inject)(推荐后者)。

还有这个:@ComponentScan(basePackages = {"com.goode.service", "com.goode.repository", "com.goode.controller", "com.goode.business", "com.goode"})可以这样替换:@ComponentScan(basePackages = {"com.goode.*"})

关于java - @Value 不从 application.properties 注入(inject)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51881056/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com