Thursday, January 25, 2018

Integrating Spring with a legacy app

Spring is a behemoth and doesn't play well with others, preferring to take over all aspects of an application - inversion of control gone wild. The best bet is to avoid it entirely, but if you're stuck with Spring for whatever reason, and want to implement something non-trivial, you're likely to need to integrate it with non-spring POJO objects - what the Spring fan-persons call "Legacy Applications"

To inject a non-spring POJO into a Spring Boot application:

  • create an ApplicationListener
  • in the listener call registerSingleton with the non-spring object
  • register the listener with the app

this allows the field to be initialized early during the application lifecycle
@RestController @SpringBootApplication public class SpringLegacy { public SpringLegacy() {} @Lazy @Autowired @Qualifier("legacyBean") Object myBean; @RequestMapping("/dir") public Object dir() { return "hello world " + myBean; } static class LegacyObject {} public static void main(final String[] args) throws Exception { Object obj = new LegacyObject(); SpringApplication app = new SpringApplication(SpringLegacy.class); ApplicationListener lis = new ApplicationListener() { boolean first = true; @Override public void onApplicationEvent(ApplicationEvent event) { if (first & event instanceof ContextRefreshedEvent) { ((GenericApplicationContext) (((ContextRefreshedEvent) event).getApplicationContext())). getBeanFactory().registerSingleton("legacyBean", obj); first = false; } } }; app.setListeners(Arrays.asList(lis));; } }
full source is
run the maven project, and then browse to localhost:8080/dir - you should see "LegacyObject" in the output

1 comment:

fabriziusuihlein said...

Casino Games For Mobile - Dr.MCD
Online slots are the leading gaming platform in the 포항 출장마사지 online gambling industry and it 경상남도 출장마사지 is no surprise 충주 출장마사지 that slots are the biggest Jun 23, 양주 출장샵 2021 안산 출장샵 · Uploaded by DGC