Im using Spring 3.0 and JDBC I'm currently experimenting with spring for a desktop application. Each time a class would need to use the datasource declared on my spring_bean_file.xml I would need to declare each of them in the xml file and again initialize each of them in my class.
Below is my xml file
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="#{T(java.lang.System).getenv(DB_URL')}"/>
<property name="username" value="#{T(java.lang.System).getenv('DB_USER')}"/>
<property name="password" value="#{T(java.lang.System).getenv('DB_PASS')}"/>
</bean>
<bean id="classA" class="com.example.ClassA">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="classB" class="com.example.ClassB">
<property name="dataSource" ref="dataSource"/>
</bean>
This is my java code:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring_bean_file.xml");
ClassA classA = (ClassA) context.getBean("classA");
ClassB classB = (ClassB) context.getBean("classB");
try {
rrRpi.generateRrRpi();
rrSpi.generateRrSpi();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//close the context
((ClassPathXmlApplicationContext) context).close();
}
Id like to know if theres a more efficient way of doing this. Whats the best approach so I wouldnt need to add a bean for each class that would use the DataSoruce. Thanks in advance guys.