Last active
October 14, 2020 02:35
-
-
Save rponte/86d74b27ca4f86d4875391e56ade51e0 to your computer and use it in GitHub Desktop.
Injecting @Autowired dependencies into self-instantiated objects with Spring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@EntityListeners(RepositoryAwareListener.class) | |
public class Cliente { | |
@Autowired // that's important! | |
private transient ClienteRepository repository; | |
// atributos da entidade | |
public List<Orcamento> orcamentosAPartirDeDeterminadoAno(int ano){ | |
return this.repository.buscaOrcamentosAPartirDoAno(this, ano); | |
} | |
} | |
public class RepositoryAwareListener { | |
@PostLoad | |
public void postLoad(Object entity) throws Exception { | |
// https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html#autowireBean-java.lang.Object- | |
ApplicationContextHolder.getInstance() | |
.getAutowireCapableBeanFactory().autowireBean(entity); // injects all dependencies | |
// another fancy solution would be using AspectJ Weaver with @Configurable annotation | |
// https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-atconfigurable | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More informations,
https://gist.github.com/rponte/e082815d9a44154351ab
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html
https://stackoverflow.com/questions/3813588/how-to-inject-dependencies-into-a-self-instantiated-object-in-spring
https://stackoverflow.com/questions/11965600/how-do-i-manually-autowire-a-bean-with-spring
http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html
https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop-atconfigurable