How to define bean properties in Spring
As i know, there are three ways to define the bean properties value in Spring.
- Properties normal way
- Properties with Shortcut
- Properties with p schema
FileNameGenerator.java
This is a simple Java class and contains two properties – name and type. Later you will use Spring to define the value into it.
package com.mkyong.common; public class FileNameGenerator { private String name; private String type; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getFileName(){ return name + "." + type; } }
1. Properties normal way
The normal way is define the value within a ‘value’ tag and enclosed with ‘property’ tag.
<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-2.5.xsd"> <bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator"> <property name="name"> <value>mkyong</value> </property> <property name="type"> <value>txt</value> </property> </bean> </beans>
2. Properties with Shortcut
Define the value in a value attribute in the ‘property’ element.
<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-2.5.xsd"> <bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator"> <property name="name" value="mkyong" /> <property name="type" value="txt" /> </bean> </beans>
3. Properties with p schema
Define the value by using the p schema as an attributes in the ‘bean’ element.
<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-2.5.xsd"> <bean id="FileNameGenerator" class="com.mkyong.common.FileNameGenerator" p:name="mkyong" p:type="txt" /> </beans>
Remember declare the xmlns:p=”http://www.springframework.org/schema/p in the Spring XML bean configuration file.
Conclusion
Which methods to use is totally base on personal preference, it will not affect the value inject into the bean properties.
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
[...] Define bean properties in Spring There are three ways to e ways to define the bean properties in Spring. [...]