As a Java developer, I often have to choose between different implementations of my interfaces. Sometimes this choice can be made once, and in some other cases I need different implementations in response to the different inputs that my program receives. In other words, I need to be able to change the implementation at runtime. This is easily achieved with a helper object that converts some key (based on user input) into a link to a suitable interface implementation.
With Spring, I can create an object like a bean and embed it wherever I need:
public class MyClass {
@Autowired
private MyHelper helper;
public void someMethod(String someKey) {
AnInterface i = helper.giveMeTheRightImplementation(someKey);
i.doYourjob();
}
}
Now, how do I implement an assistant? Let's start with this:
@Service
public class MyHelper {
public AnInterface giveMeTheRightImplementation(String key) {
if (key.equals("foo")) return new Foo();
else if (key.equals("bar")) return new Bar();
else ...
}
}
. , , , , , . , Foo :
@Service
public class Foo {
@Autowired
private VeryCoolService coolService;
...
}
... Foo, MyHelper, coolService.
, :
@Service
public class MyHelper {
@Autowired
private Foo foo;
@Autowired
private Bar bar;
...
public AnInterface giveMeTheRightImplementation(String key) {
if (key.equals("foo")) return foo;
else if (key.equals("bar")) return bar;
else ...
}
}
. - :
@Service
public class MyHelper {
@Autowired
private ApplicationContext app;
public AnInterface giveMeTheRightImplementation(String key) {
return (AnInterface) app.getBean(key);
}
}
Spring ApplicationContext.
ServiceLocatorFactoryBean:
public interface MyHelper {
AnInterface giveMeTheRightImplementation(String key);
}
@Bean
ServiceLocatorFactoryBean myHelper() {
ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean();
bean.setServiceLocatorInterface(MyHelper.class);
return bean;
}
Spring, , .