Configure with Java Annotations
Last Updated on: January 13, 2021 pm
Java Annotations
Meta-data about the class.
Processed aannotations at compile time and run time.
Inversion of Control
Development Process
Enable component canning in Spring config file
Spring will scan the package recursively.
1
<context:component-scan base-package="com.luv2code.annotations"/>
Add the @Component Annotation to your Java class.
1
2
3@Component // use Default Bean Name
public class TennisCoach {
}Retrieve bean from Spring container.
Same as before.
Dependency Injection
AutoWiring
Spring wil look for a class that matches the property.
Match by type: Class or Interface
Spring will inject it automatically.
Constructor Injection
Define a dependency interface and class
Define FortuneService
interface and BadFortuneService
Class.
1 |
|
Create a constructor for injections
1 |
|
Configure with @Autowired annotation
Add @Autowired
annotation to the constructor.
Setter Injection
Create setter methods in your class for injections.
Configure the dependency injection with Autowired Annotation.
1 |
|
Method Injection
1 |
|
Field Injection
- Configure the dependency injection with
@Autowired
, no need for setter method. - Directly set the
@Autowired
annotation to the field. Spring will injection theFortuneService
implementation directly to the class, using Java technology called Reflection.
Which injection should I use?
Choose a style and stay consistent in your project.
Qualifiers for Dependency Injection
- What if there is more than one implemetations to choose when injecting?
- Use the
@Qualifier
with the Default Name of the implementation. - For example, Class Name is
HappyFortuneService
, then the Default Name should behappyFortuneService
.
You can use
@Qualifier
to all kinds of injections.
Bean Scope and Lifecycle
Scope
@Scope("Singleton")
@Scope("Prototype")
Lifecycle Methods
- Define your methods for initialization and destroy.
@PostConstruct
@PreDestroy
- Add Annotations to these methods.
Note: For “prototype” scoped beans, Spring does not call the @PreDestroy method. Gasp!
Reference: Udemy, Spring & Hibernate for Beginners (including SpringBoot)