通过ConfigurableApplicationContext,实现不同的配置加载不同的实现类

使用ConfigurableApplicationContext接口直接操作Bean的注册、获取和删除,进而实现不同的配置加载不同的实现类。

1.创建并配置Bean

首先,在应用中定义多个实现相同接口的不同Bean。如下,有两个实现NotificationService接口的类

public interface NotificationService {
    void sendNotification();
}

@Service("emailService")
public class EmailNotificationService implements NotificationService {
    @Override
    public void sendNotification() {
        System.out.println("Sending email notification.");
    }
}

@Service("smsService")
public class SmsNotificationService implements NotificationService {
    @Override
    public void sendNotification() {
        System.out.println("Sending SMS notification.");
    }
}

 2.动态获取Bean

在需要根据配置选择服务的地方,可以通过ConfigurableApplicationContext的API来获取特定名称的Bean。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class NotificationServiceSelector {

    @Autowired
    private ConfigurableApplicationContext context;

    public void selectAndNotify(String serviceName) {
        try {
            // 根据配置的服务名获取Bean
            NotificationService service = context.getBean(serviceName, NotificationService.class);
            if (service != null) {
                service.sendNotification();
            } else {
                System.out.println("Service with name " + serviceName + " not found.");
            }
        } catch (Exception e) {
            System.out.println("Error fetching service: " + e.getMessage());
        }
    }
}

3.应用配置选择

在业务逻辑中,调用NotificationServiceSelector并传递配置决定的服务名称,以选择并执行相应的服务。

@Service
public class BusinessService {
    
    @Autowired
    private NotificationServiceSelector selector;
    
    public void processNotification() {
        // 假设服务类型是从配置中读取的
        String selectedService = getConfiguredServiceType(); // 实现此方法以从配置中获取服务类型
        selector.selectAndNotify(selectedService);
    }
    
    // 假设的配置读取方法
    private String getConfiguredServiceType() {
        // 从配置文件、数据库或环境变量读取服务类型
        return "emailService"; // 示例返回固定值,实际应用中应替换为真实的配置读取逻辑
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值