Spring — java.util.Properties DI Parameters | Code Factory

Code Factory
2 min readJan 17, 2021

--

Donate : Link

WordPress Blog : Link

Applications… : Link

Spring Tutorial Index Page: Link

  • For Property, inside dtd based configuration we can pass required key-value pairs.
<bean id="" class="">
<property name="">
<props>
<prop key="fname">ABC</prop>
</props>
<property>
</bean>
  • For Map we use <entry> tag but for Property we use <props> tag.

Create Java Project

  • Open Eclipse
  • Go to File -> New -> Others… -> Java Project
  • Create DI-Properties project
  • Right click on project -> Build Path -> Configure Build Path -> Libraries tab -> Add External JARs
    - commons-logging-X.X.jar
    - spring-beans-X.X.X.jar
    - spring-context-X.X.X.jar
    - spring-core-X.X.X.jar
    - spring-expression-X.X.X.jar
  • * You can find dtd information from spring-beans-X.X.X.jar -> org -> springframework -> beans -> factory -> xml -> spring-beans.dtd (line no 36 & 37)

spring.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="t" class="com.codeFactory.beans.Test">
<property name="driver">
<props>
<prop key="driverClass">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://localhost:3306/test</prop>
<prop key="user">username</prop>
<prop key="password">password</prop>
</props>
</property>
</bean>
</beans>

Test.java

package com.codeFactory.beans;import java.util.Map.Entry;
import java.util.Properties;
/**
* @author code.factory
*
*/
public class Test {
private Properties driver;
public void setDriver(Properties driver) {
this.driver = driver;
}
public void print() {
System.out.println("Driver Info: " + driver);
for(Entry<Object, Object> obj : driver.entrySet()) {
System.out.println(obj.getKey() + " : " + obj.getValue());
}
}
}

Client.java

package com.codeFactory.test;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.codeFactory.beans.Test;/**
* @author code.factory
*
*/
public class Client {
public static void main(String... args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/codeFactory/resources/spring.xml");

Test t = (Test) context.getBean("t");
t.print();
}
}

Output:

Driver Info: {driverClass=com.mysql.jdbc.Driver, user=username, password=password, url=jdbc:mysql://localhost:3306/test}
driverClass : com.mysql.jdbc.Driver
user : username
password : password
url : jdbc:mysql://localhost:3306/test

--

--