使用
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"; // 示例返回固定值,实际应用中应替换为真实的配置读取逻辑
}
}