6 Nisan 2018 Cuma

Service Locator Pattern with Spring Boot

1. Create a base type for your services

public interface MyService {
}

2. Create an enumaration for your service types and implement its toString() method. Return bean name in toString method.

public enum MyServiceType {
    MY_SERVICE_1("my_service_1"),
    MY_SERVICE_2("my_service_2");

    private final String value;

    MyServiceType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }
}

3. Create a factory interface

public interface MyFactory {
    MyService getService(MyServiceType type);
}

4. Create your service types and register them as bean with bean names

@Bean("my_service_1")
@Component
public class MyService1 implements MyService {
    ...
}

@Bean("my_service_2")
@Component
public class MyService2 implements MyService {
    ...
}

5. Register your factory to spring context

@Bean
public FactoryBean serviceLocatorFactoryBean() {
ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(MyServiceFactory.class);
return factoryBean;
}

6. Get your bean using your factory and enum value.

@Autowired
private MyServiceFactory myServiceFactory;

public void myMethod() {
    MyService service = this.myServiceFactory.getService(MyServiceType.MY_SERVICE_1);
    ...
}

Hiç yorum yok:

Yorum Gönder