自前でnewしたオブジェクトにSpringのBeanをinjectする方法
タイトルの通りです。
トランザクションスクリプトではなくドメインモデル的に作ろうと思うと、ドメインオブジェクトの中からSpringコンテキスト配下のBeanにアクセスしたいケースが出てきます。
こうするとできるよ、というのがわかったので記録しておきます
AutowireCapableBeanFactory の autowireBeanを通せばいいようです
class Entity { @Autowired private SomeService someService; } @Component class EntityFactory { @Autowired private AutowireCapableBeanFactory beanFactory; Entity create() { Entity entity = new Entity(); beanFactory.autowireBean(entity); return entity; } }