Monday, April 20, 2015

Issue with Key Names During DriverManagerDataSource Spring Bean Initialization

So I found a little something while loading a DriverManagerDataSource in Spring.

The DriverManagerDataSource is a class, the objects of which you usually initialize from within the bean configuration (Application Context) XML  file in Spring for configuring a DataSource. And this is how people usually do it:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="
jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="myuser" />
</bean> 
However, for some reason, I had to do this in code. Now, spring gives you a constructor, which takes a URL and a Properties object as arguments. Signature:
DriverManagerDataSource(String url, Properties conProps)
So I assumed the keys in the conProps object would be the same as the property names in the XML. But turns out I was wrong. The keys that the conProps object must have are actually different. Here's how I did it:
Properties conProps = new Properties();
conProps.put("user", "myuser");
conProps.put("driverClassName", "com.mysql.jdbc.Driver");
DriverManagerDataSource dataSource = new DriverManagerDataSource("
jdbc:mysql://localhost:3306/mydb", conProps);
So the key for the 'username' property is actually 'user' when using the constructor with Properties. Have I found a bug? ;)
Nonetheless, that took a good 15 mins of hair-pulling until I noticed.

Note: I am using Spring 4.1.5.

No comments: