Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure DataSource from Java (without XML)

I'm starting to develop a test application with Spring MVC and Hibernate, and I have a question about the database configuration.

I know I am able to define the datasource through the application-context.xml, like

<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/testdb"/>
    <property name="username" value="root"/>
    <property name="password" value="password"/>
</bean>

But I wanted not to use XML at all, so I created a configuration class in which I wanted to load a DataSource object, with a method similar to this:

 @Bean
public DataSource dataSource() {
    ...
}

My question is: how can I get a DataSource instance that points to my MySQL schema? If there are several options, which is the best in your opinion?

I want to use a MySQL database, not an embedded one

Thanks

like image 990
r.rodriguez Avatar asked Mar 24 '23 05:03

r.rodriguez


1 Answers

As I was working with Spring MVC, I solved it in the following way:

@Bean
public DriverManagerDataSource getMySQLDriverManagerDatasource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setPassword("password");
    dataSource.setUrl("jdbc:mysql://localhost:3306/mytestdb");
    dataSource.setUsername("root");
    return dataSource;
}
like image 161
r.rodriguez Avatar answered Mar 26 '23 21:03

r.rodriguez