We can fill data to a Java Bean defined in the Spring configuration xml in several ways.
The following sections show to inject value to the name
and type
properties defined
in the MyClass.
package com.java2s.common public class MyClass { private String name; private String type; public String getName() { return name;/*from w w w . j ava 2 s . c om*/ } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
The following code shows how to inject 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="myClass" class="com.java2s.common.MyClass"> <property name="name"> <value>java2s</value> </property> <property name="type"> <value>txt</value> </property> </bean> </beans>
After loading the myClass from Spring configuration xml file the name and type properties are set to java2s and txt respectively.
We can use shortcut property tag to fill value to Java bean properties in the following way.
The property tag can have a value attribute. We put our value there.
<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="MyClass" class="com.java2s.common.MyClass"> <property name="name" value="java2s" /> <property name="type" value="txt" /> </bean> </beans>
We can even fill the properties when declaring the Java Bean in the bean tag.
<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="MyClass" class="com.java2s.common.MyClass" p:name="java2s" p:type="txt" /> </beans>
In order to use the p schema we have to declare the
xmlns:p="http://www.springframework.org/schema/p
in
the Spring XML bean configuration file.