在运行时注入bean读取属性文件 [英] Inject bean at runtime reading properties file

查看:58
本文介绍了在运行时注入bean读取属性文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 MailConsoleService 类和一个 MailSMTPService 类,都实现了 MailService 界面。我有一个 EmailJob 类,它从数据库加载用户并通过Spring注入的MailService实例发送电子邮件。

Suppose I have a class MailConsoleService and a class MailSMTPService, both implement the MailService interface. I have a class EmailJob which loads the users from a db and send an email through a MailService instance injected by Spring.

如何读取属性并在运行时确定要注入哪个 MailService 实现?显然,该属性可以在应用程序运行时随时更改。

How could I read a properties and determine at runtime which implementation of MailService to inject? The properties could change at any time the app is running, obviously.

我已经考虑过创建一个工厂bean,它将正确的实例从spring容器返回到 EmailJob ,但我不知道如何实现。

I've thought about to create a factory bean which returns the right instance from the spring container to EmailJob but I don't know how to implement this.

注意:我所有的bean都配置为Singleton范围,所以我想至少我必须更改为Prototype EmailJob

Note: All my beans are configured to Singleton scope, so I guess I'll have to change to Prototype EmailJob at least.

注2:在工厂bean中我该如何避免每次都读取属性文件?

Note 2: In the factory bean how could I avoid to read the properties file each time?

谢谢!

推荐答案

您可以执行以下操作:

@Component
public class Factory {

@Autowired
private MailService mailConsoleService;

@Autowired
private MailService mailSmtpService;

@Value("${mailServiceProperty}")
private String mailServiceProperty;

public MailService getMailService() {
    switch (mailServiceProperty) {
    case "CONSOLE":
        return mailConsoleService;

    case "SMTP":
        return mailSmtpService;
    }       
    return null;
}

}

另外,您需要使用 PropertyPlaceholderConfigurer

这篇关于在运行时注入bean读取属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆