Why would you need to configure Spring project?
Configuring enables a developer to achieve loose coupling in a project. You wouldn’t want a project to break when you need to make changes to it. For example, Honda gets its parts from different companies. Tires from Goodyear, stereo from Boss etc… But one day, Honda has a fight with Goodyear because their tires aren’t that good anymore. Now Honda needs a new company to provide tires. If the project was loosely coupled, all you have to change is the dependent(tires) and inject it into the program. So swap the tires in the configuration file with another company /*I don’t know any tire companies*/. That’s Dependency Injection!
Beans
A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container.
Configuring using Java Annotations
Java Annotations are a modern way of configuring Spring Application. They are, in short, meta-data about a class or Special labels added to Java classes. They are processed at compile time or runtime for special processing.
Examples of Java Annotations
@Override
Benefits of Java Annotations
XML configurations can be very verbose. In XML config file, every bean must be listed and if your project contains a large number of beans, it will be too much work
Spring beans can be configured using annotations
Annotations minimizes the XML configurations
Spring will scan your java classes and automatically register the bean into a spring container.
Configuring using Java code
Development Process
- Create a java Class and annotate as @Configuration
- Add component scanning support: @ComponentScan (Optional)
- Read Spring Java configuration class
SpringAnnotationContext context = new SpringAnnotationContext(SpringAnnotationApplication.class) - Retrieve bean from Spring container
Use the getBean method
Defining a Bean with Java code
- Define the methods to expose the bean by @Bean
- Inject bean dependencies
- Read the Spring Java Configuration class
SpringAnnotationContext context = new SpringAnnotationContext(SpringAnnotationApplication.class) - Retrieve bean from Spring Container
Use the getBean method
Auto-wiring
For dependency Injection, Spring can use spring auto wiring. The way auto-wiring works is that Spring will look for a class that matches the property.
Matchers by type: class or interface
Spring will inject the dependency automatically so you, the programmer, don’t have to worry about extra boilerplate code.
How does auto-wiring work?
- Spring will scan for @Components. The @Component is placed above the class that you want to be injected.
- Place the @Autowired above a constructor.
