Bean injection inside a JPA @Entity

前端 未结 3 2146
抹茶落季
抹茶落季 2020-11-27 05:31

Is it possible to inject beans to a JPA @Entity using Spring\'s dependency injection?

I attempted to @Autowire ServletContext but, while the server did

3条回答
  •  渐次进展
    2020-11-27 06:16

    After a long time I stumbled across this SO answer that made me think of an elegant solution:

    • Add to your entities all the @Transient @Autowired fields you need
    • Make a @Repository DAO with this autowired field: @Autowired private AutowireCapableBeanFactory autowirer;
    • From your DAO, after fetching the entity from DB, call this autowiring code: String beanName = fetchedEntity.getClass().getSimpleName(); autowirer.autowireBean(fetchedEntity); fetchedEntity = (FetchedEntity) autowirer.initializeBean(fetchedEntity, beanName);

    Your entity will then be able to access the autowired fields as any @Component can.

提交回复
热议问题