Extrayendo propiedades de beans xml en java

Hello guys I'm quite new at Web Development and I'm stuck on a problem here. I want my java program to connect to a database using Jdbs connector but instead of hard coding the database variables I want my program to read an xml file where the values are stored in beans. The lines I want to be read are stored in applicationContext.xml file as follows:

<bean id="ObjectMapperFactory" scope="singleton" class="someClass"/>
<bean id="UgcDataSource" class="org.apache.commons.dbcp.BasicDataSource">
 <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
 <property name="username"><someUser</value></property>
 <property name="password"><somePassword</value></property>
 <property name="url"><value>jdbc:mysql://localhost:3306/dbName?autoReconnect=true</value></property>
 <property name="defaultAutoCommit"><value>false</value></property>
 <property name="maxActive"><value>20</value></property>
 <property name="maxIdle"><value>3</value></property>

And after reading it I want these variables to be stored in strings as such:

String url = "jdbc:mysql://localhost:3306/dbName"
String username = "someUser"
String password = "somePassword"

So what I'm looking for is a way to extract those 3 values, any suggestions? Much appreciated!

preguntado el 28 de agosto de 12 a las 12:08

Why not use the data source? Also, that's significantly more verbose than it needs to be, even if you don't use the p: name space. -

Thank you for such a quick reply sir, but could you please clarify as this is quite mind boggling for me at the moment. -

Well, let's take a step back: why do you want those strings in your Java code? -

@DaveNewton it's part of my training programme of my placement, I already got querying MySQL database via java program done, but the guys want me to get database values from the xml file. -

Why on earth would they want that? Are you sure that's what they want? As far as I'm concerned that's a bizarre requirement-in real life you'd either use a property placeholder configurator, or you'd use the source more directly. Was any explanation or rationale given? -

1 Respuestas

With Spring you can use the @Value Annotation like so

private String url;

Respondido 28 ago 12, 12:08

Thank you, I managed to find the answer I was looking for doing some research on @Value - Mantas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.