Gerenciando objetos complexos com Spring
Instancie e gerencie objetos caros, complexos e de outros frameworks com Spring
Algumas vezes precisamos que o Spring cuide da criação e injeção de objetos complexos ou de outros frameworks que usamos na nossa aplicação. Dessa forma, evitamos ter que ficar dando new em APIs de terceiros em vários locais da aplicação e passamos apenas a recebê-los como dependências das nossas classes.
Para que isso seja possível, podemos ensinar ao Spring como criar estes objetos, além de explicitar o escopo na qual eles devem ser registrados, sua prioridade, se usaremos criação preguiçosa, entre outros detalhes. Para isso, usamos a anotação @Bean
em um método de uma classe gerenciada pelo Spring, criamos o objeto complexo dentro do método anotado e retornamos sua instância. No final das contas, o método funcionará como uma fábrica para um determinado tipo de objeto.
Por exemplo, para criar uma instância pré-configurada da classe XStream
, que é uma biblioteca famosa de serialização e deserialização de XML e JSON, podemos ter uma classe semelhante a esta:
@Component
public class CriadorDeXStream {
@Bean
public XStream xStream() {
XStream xstream = new XStream(new StaxDriver());
xstream.registerConverter(new CustomDateConverter());
// mais configurações do framework
return xstream;
}
}
No caso acima, sempre que uma classe solicitar uma instância de XStream
, o Spring se encarregará de invocar o método anotado com @Bean
e colocar o objeto retornado em escopo de aplicação. Se necessário, podemos alterar o escopo do bean criado através da anotação @Scope
:
@Bean
@Scope("request")
public XStream xStream() {
// ...
}
Portanto, qualquer bean gerenciado pelo Spring que precisar da API do XStream terá apenas que declará-la como dependência através da anotação @Autowired
, como no código a seguir:
@Service
public class GeradorDeXml {
@Autowired
private XStream xStream;
public String geraXml(Cliente cliente) {
String xml = xStream.toXML(cliente);
return xml;
}
}
Injetar esta mesma instância do XStream
em um managed bean ou conversor do JSF seria tão simples quanto o código acima. Bastaria ter as classes do JSF gerenciadas pelo Spring como já sabemos.
Práticas como estas ajudam a diminuir o acoplamento entre as classes da aplicação, além de tirar proveito do container do Spring e de todos seus recursos para gerenciar um objeto, como ciclo de vida, controle transacional, auditoria, segurança etc. Por esse motivo, sempre favoreça a responsabilidade de criar e gerenciar objetos caros, complexos e de terceiros para seu container IoC/DI.
Para conhecer e entender melhor o container do Spring e algumas de suas configurações avançadas, conheça nosso curso JSF 2 com Spring.
O suporte a anotações do Spring existe desde sua versão 3.0 e certamente é tendência daqui para frente. A idéia é diminuir o uso de XML ao trabalhar com Spring e passar a configurá-lo através de código Java.
E você? Tem utilizado a anotação @Bean
para criar algum tipo de objeto na sua aplicação?
Desenvolvedor e instrutor na TriadWorks