Configuration Metadata
Where we declare beans and it's dependency.The container knows what to instantiate and configure using configuration metadata .
Three ways to Configuring Metadata
-
XML
- Beans and their dependencies are declared in an XML file (commonly
config.xmlorapplicationContext.xml). - Spring container reads the XML file and creates objects accordingly.
- Beans and their dependencies are declared in an XML file (commonly
-
Java annotations
- Done by annotating classes, methods, or fields.
- Use
@Component,@Autowired @Autowired– Most common annotation; tells the IoC container to inject dependencies.
-
Java code
@Configuration– Marks a class as a source for bean definitions.@Bean– Indicates that a method’s return object should be managed by the IoC container.
Spring XML DI Example - Project Procedure
- Create Maven Project : Set up project structure using Maven.
- Add Dependencies : Add Spring Core and Spring Context in
pom.xml. - Create Bean (
Student.java) : Plain Old Java Object (POJO) with propertiesidandname. -
Create Configuration File (
config.xml) :Define the student1 bean and set properties. -
Setter Injection : Use setter methods in
Student.javato injectidandname. - Main Class :
- Load Spring
ApplicationContext. - Retrieve Student bean and use it.
- Load Spring
ApplicationContext container= new ClassPathXmlApplicationContext("Config.xml");
Object obj =container.getBean("student1");
Student s1=(Student)obj;
Key Points:
Bean : An object managed by the IOC container.
DI – Container injects dependencies.
IoC – DI is Spring’s way of implementing IoC.
Github Code : Configuration Metadata