01 - Spring Beans & ApplicationContext
Spring Beans
Bean é um Objeto Java criado, configurado e gerenciado pelo Contêiner Spring IoC (Inversion of Control).
O que transforma um Objeto Java em um Bean?
O objeto precisa ser registrado no Contêiner Spring usando anotações como:
- @Controller
- @Service
- @Repository
- @Component
- @Configuration
Spring Bean x POJO
POJO (Plain Old Java Object):
- é uma classe Java simples
- não estende nenhuma classe específica
- não implementa nenhuma interface obrigatória
- não possui nenhuma dependência, como Hibernate ou qualquer framework
Exemplo de POJO:
# no dependencies, interfaces and frameworks
public class UserService() {
}
UserService service = new UserService();
Exemplo de Bean:
@Service
public class UserService() {
}
Como criar um Bean
- Usando anotações estereótipo (@Controller, @Service, @Repository, @Component).
@Controller
public class UserController {
}
- Usando @Bean dentro de uma classe @Configuration.
@Configuration
public class AppConfig {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
# Spring will execute the command below and register it as a Bean:
ObjectMapper mapper = new ObjectMapper();
# Example using a third-party client:
public class StripeClient {
}
# You cannot add: @Component into StripeClient, so:
@Configuration
public class StripeConfig {
@Bean
public StripeClient stripeClient() {
return new StripeClient();
}
}
- Usando configuração XML (abordagem legada) Exemplo:
<beans>
<bean
id="paymentService"
class="com.example.PaymentService"/>
</beans>
# Spring creates and registers it
new PaymentService();
ApplicationContext
É uma implementação do Contêiner Spring IoC. Existe um contêiner antigo “BeanFactory” (mais simples)
Contêiner IoC x ApplicationContext
Contêiner IoC -> É um conceito (o mecanismo que cria, configura e gerencia os objetos).
Exemplo:
# The Spring finds this class:
@Service
public class PaymentService(){
}
# And create a new instace to store inside the container
PaymentService paymentService = new PaymentService();
ApplicationContext -> É uma Interface Spring que implementa esses conceitos com mais funções extras, este objeto representa o contêiner em uma aplicação Spring.
Exemplo:
# In that way you have all the registered Beans
ApplicationContext context = SpringApplication.run(Application.class, args);
# You can pick one manually
PaymentService paymentService = context.getBean(PaymentService.class);
Aplicação Spring
|
|
v
+--------------------+
| ApplicationContext |
| |
| Registro de Beans |
| |
| UserService |
| OrderService |
| Repository |
+--------------------+
|
|
v
Dependency Injection
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- Iniciar JVM |
- Criar ApplicationContext |
- Escanear classes |
- Encontrar @Component, @Service, @Repository… |
- Criar Beans |
- Injetar dependências |
- Iniciar aplicação