Explain configuration file in Spring (config.xml)
Steps:
Create maven project
Adding dependencies => spring core, spring-context
Creating beans — java POJO
Creating configuration file => config.xml (or any suitable name)
Setter injection
Main class: which can pull the object and use it.
Creating beans — java POJO
1. create a class Student.java
→ add getter and setters
→ add constructors
→ add toString()
Creating configuration file => config.xml
→ we can student object using a new keyword but it does achieve loose coupling so we will create a new configuration file
in which we have to specify that we have ‘bean’ called student and we need to specify which properties does the student have and we have put those values.
Finally, we will give the path of the configuration file to the spring container. So spring container will simply create an object,
it will manage its life cycle and we can get that object.
→ create a new XML file, config.xml
→ 1. first add the namespace of spring (goto spring 5 documentation → configuration metadata)
<beans xmlns=”http://www.springframework.org/schema/beans"
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id=”…” class=”…”>
<! — collaborators and configuration for this bean go here →
</bean>
<bean id=”…” class=”…”>
<! — collaborators and configuration for this bean go here →
</bean>
<! — more bean definitions go here →
</beans>
Note: in <beans> specify name and class
e.g <bean class=”com.springcore.Student” name=”student1"> </bean>
Types of injection
1. Setter injection
2. Constructor injection