gpt4 book ai didi

java - 如何将 java.util.Properties 对象提供给 spring 以解析 spring 中的属性值,例如 Properties 对象中的 ${mail.port}

转载 作者:行者123 更新时间:2023-11-30 08:14:56 26 4
gpt4 key购买 nike

您好,我正在创建一个独立的 Spring 应用程序 jar,它将是一个实用程序服务,因此我将获得 java.util.Properties 对象,并且我需要在我的 Spring 应用程序中使用此属性,

所以我需要做的是创建一个类,在其构造中将 Properties 对象作为参数

我所做的是

public class MailService {
public MailService(Properties properties) {
PropertySourcesPlaceholderConfigurer pops = new PropertySourcesPlaceholderConfigurer();
pops.setProperties(properties);
ClassPathXmlApplicationContext ctx = null;
try {
ctx = new ClassPathXmlApplicationContext("/resources/xml/spring/mailservice_context.xml");

} catch (Exception e) {
e.printStackTrace();
} finally {
if (ctx != null) {
ctx.close();
ctx = null;
}
}

}
}

我想要从我在 MailService 的构造函数中传递的属性对象中的“mail.host”、“mail.port”

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${mail.host}" />
<property name="port" value="${mail.port}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="javaMailProperties">
<props>
<prop key="mail.transport.protocol">${mail.transport.protocol}</prop>
<prop key="mail.smtps.auth">${mail.smtps.auth}</prop>
<prop key="mail.smtps.starttls.enable">${mail.smtps.starttls.enable}</prop>
<prop key="mail.debug">${mail.debug}</prop>
</props>
</property>
</bean>

我如何从java的属性对象中获取这个值,我正在使用spring 4.1

最佳答案

添加这两行:

    ctx.addBeanFactoryPostProcessor(pops);
ctx.refresh();

之后:

ctx = new 
ClassPathXmlApplicationContext("/resources/xml/spring/mailservice_context.xml");

这将设置 ClassPathXmlApplicationContext 中的属性,并且 .refresh() 将加载它们。

关于java - 如何将 java.util.Properties 对象提供给 spring 以解析 spring 中的属性值,例如 Properties 对象中的 ${mail.port},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29794270/

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