This project works on different techniques of creating Spring Beans and autowiring them and also working with Qualifier and Scope of the Beans. Please look through the commit history section below for changes in each iteration. Each iteration shows different types of creating beans and working with them
Before you begin, ensure you have met the following requirements:
- Java Development Kit (JDK) 17 or later
- Spring framework
- Maven for building the project
Follow these steps to set up and run the Spring security Learner Microservice:
-
Clone this repository:
git clone https://github.com/yr5913/spring-beans.git cd spring-beans
-
Build the microservice:
mvn clean install
-
Run the microservice:
java -jar target/spring-beans.jar
- Usage of @Beans Annotation -- First commit created spring beans
- generates NoUniqueBeanDefinitionException due to ambiguity as multiple beans of same class are created
- corrected NoUniqueBeanDefinitionException by specifying the proper name of the bean to avoid ambiguity
- Usage of property name, value in the @Bean Annotation - How to provide user defined names to beans
- usage of @Primary annotation to specify the default bean to the spring
- Usage of @Component Annotation
- Usage of @PostConstruct Annotation
- Usage of @PreDestroy Annotation
- Usage of registerBean() Method
- Created Two different types of beans that has a relationship between them but didn't autowire them
- Autowired beans using method call
- Autowired beans using method parameters
- Autowired using @Autowired annotation on class fields
- Usage of @Autowired annotation with its parameter required set to false
- Autowired using @Autowired annotation on setter method
- Autowired without using @Autowired annotation anywhere -- by default spring does the constructor autowiring if there is only one constructor
- Autowired using @Autowired annotation on constructor -- best practice
- Multiple beans, using @Autowired annotation on constructor where the parameter name doesn't match with any of the multiple beans -Error UnsatisfiedDependencyException
- Correct the above by defining on of the beans as primary
- Usage of @Qualifier -- Also we can ge the custom bean we require from the multiple beans available by using Qualifier to mention the bean we need.
- Circular Dependency -- error is generated
- Implemented a Simple Project with these dependencies-- Person has a Vehicle, Vehicle uses Vehicle Services to Play Music and run on Tyres, There are multiple music players, tyres and default ones should be configured
- Bean Scope - Singleton Pattern - check Main class for the code
- Testing the default Eager initialization by Spring
- Testing the Lazy initialization by Spring
- Bean Scope - Prototype Pattern - check Main class for the code