Spring Core- Defining Bean Properties by Shortcut
Spring supports a shortcut for specifying the value of a simple type property.
In case of creating beans using setter method, we use below Spring configuration.
1 2 3 4 |
<bean id="school" class="com.code2succeed.core.school.School"> <property name="name" value="Code2Succeed"/> <property name="noOfFaculties" value="100"/> </bean> |
For creating beans using constructor, we use below Spring configuration.
1 2 3 4 |
<bean id="school" class="com.code2succeed.core.school.School"> <constructor-arg value="Code2Succeed"/> <constructor-arg value="100"/> </bean> |
Since Spring 2.0 another convenient shortcut to define properties was added. It consists of using the p schema to define bean properties as attributes of the element. This can shorten the lines of XML configuration.
The below example demonstrate creation of beans using p schema.
1) School.java
We have a School bean which contain name and noOfFaculties as instance variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.code2succeed.core.school; public class School { private String name; private int noOfFaculties; public School(String name, int noOfFaculties) { this.name = name; this.noOfFaculties = noOfFaculties; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNoOfFaculties() { return noOfFaculties; } public void setNoOfFaculties(int noOfFaculties) { this.noOfFaculties = noOfFaculties; } } |
2) Spring Configuration.
Bean creation using p schema.
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="school" class="com.code2succeed.core.school.School" p:name="Code2Succeed" p:noOfFaculties="100"/> </beans> |
3) Load bean xml and run the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.code2succeed.core.school; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "springbeans.xml"); School school = (School) context.getBean("school"); System.out.println("Name : "+school.getName()); System.out.println("No of Faculties : "+school.getNoOfFaculties()); } } |
4) Output.
Name : Code2Succeed
No of Faculties : 100