Skip to content

Instantly share code, notes, and snippets.

@OsaSoft
Last active September 26, 2017 16:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save OsaSoft/9832ab583dfee2576d01bf08ec14546e to your computer and use it in GitHub Desktop.
Save OsaSoft/9832ab583dfee2576d01bf08ec14546e to your computer and use it in GitHub Desktop.
Spring Autowiring in instances that are not managed Spring beans
class InjectReadyClass {
@Autowired
public MyCoolService myCoolService; //public just for showing purposes
InjectReadyClass(ApplicationContext ctx) {
ctx.getAutowireCapableBeanFactory().autowireBeanProperties(
this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false
);
}
}
@Service
class SomeService {
@Autowired
ApplicationContext ctx;
void someServiceMethod() {
...
InjectReadyClass injectReadyInstance = new InjectReadyClass(ctx);
assert injectReadyIntance.myCoolService != null //just to show it gets injected properly
...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment