Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active October 14, 2020 02:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rponte/86d74b27ca4f86d4875391e56ade51e0 to your computer and use it in GitHub Desktop.
Save rponte/86d74b27ca4f86d4875391e56ade51e0 to your computer and use it in GitHub Desktop.
Injecting @Autowired dependencies into self-instantiated objects with Spring
@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
}
}