3 annotation bean scope, java code config
8 Spring Configuration with Java Annotations - Bean Scopes and Lifecycle Methods
8.1 Bean Scopes
8.2 Bean Lifecycle Methods - Annotations
Development Process
Define your methods for init and destroy
Add annotations: @PostConstruct and @PreDestroy
@PostConstruct: Code will execute after constructor and after injection of dependencies
@PreDestroy: Code will execute before bean is destroyed
e.g.
Note: For "prototype" scoped beans, Spring does not call the @PreDestroy method. Gasp!
In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.
Thus, although initialization lifecycle callback methods are called on all objects regardless of scope,in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding.
9. Spring Configuration with Java Code
Instead of configuring Spring container using XML
Configure the Spring container with Java cod
3 ways of configuring Spring Container
Full XML config
XML Component Scan
Java Configuration Class
e.g. 1
e.g.2
e.g.3
9.1 Development Process
Create a Java class and annotate as @Configuration
Add component scanning support:@ComponentScan(optional)
Read Spring Java configuration class
Retrieve bean from Spring container
e.g.3
9.2 Defining Beans in Spring
Development Process:
Define method to expose bean
Inject bean dependencies
Read Spring Java configuration class
Retrieve bean from Spring container
9.3 Injecting Values from Properties File
Development Process
Create Properties File
Load Properties File in Spring config
Reference values from Properties File
e.g.2
Last updated
Was this helpful?