Skip to content

Instantly share code, notes, and snippets.

@rponte rponte/Cliente.java
Last active Jun 13, 2019

Embed
What would you like to do?
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
}
}
You can’t perform that action at this time.