1 回答
TA贡献1816条经验 获得超4个赞
也许你可以使用 org.springframework.beans.factory.config.ServiceLocatorFactoryBean,定义一个 MessageProcessorService:
public interface MessageProcessorService {
void process(Message message);
}
然后是服务工厂的接口:
public interface MessageProcessorServiceFactory {
MessageProcessorService getMessageProcessorService(String messageType);
}
在您的配置类中,您可以创建服务工厂并实现不同的消息处理器:
@Configuration()
public class Config {
@Bean
public ServiceLocatorFactoryBean serviceLocatorFactoryBean() {
ServiceLocatorFactoryBean serviceLocatorFactoryBean = new ServiceLocatorFactoryBean();
serviceLocatorFactoryBean
.setServiceLocatorInterface(MessageProcessorServiceFactory.class);
return serviceLocatorFactoryBean;
}
@Bean("typeB")
public MessageProcessorService typeBProcessorService() {
return new MessageProcessorService() {
@Override
public void process(Message message) {
System.out.println("Processing a B type message");
}
};
}
@Bean("typeA")
public MessageProcessorService typeAProcessorService() {
return new MessageProcessorService() {
@Override
public void process(Message message) {
System.out.println("Processing an A type message");
}
};
}
@Bean
public SomeService someService(){
return new SomeService();
}
}
让 SomeService 成为您接收消息的服务:
@Service
public class SomeService {
@Autowired
private MessageProcessorServiceFactory factory;
public void doSomething(Message message) {
String messageType = message.getType();//Type must be typeA or typeB, matching processor beans names
MessageProcessorService messageProcessorService = factory.getMessageProcessorService(messageType);
messageProcessorService.process(message);
}
}
因此,通过使用 MessageProcessorServiceFactory,您可以为每种不同的消息类型获得不同的处理器实现。
希望能帮助到你
添加回答
举报