Main Tutorials

How to autowire DataSource in JdbcDaoSupport

A Simple DAO class extends JdbcDaoSupport, but, unable to inject or @autowired a “dataSource”, the method setDataSource is final, can’t override.

UserDetailsDaoImpl.java

package com.mkyong.users.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao {

	//Error, cannot override the final method from JdbcDaoSupport
	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
}

Solution

To quickly fix it, uses @PostConstruct to inject the dataSource like this :

UserDetailsDaoImpl.java

package com.mkyong.users.dao;
import javax.sql.DataSource;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao {

	@Autowired
	private DataSource dataSource;

	@PostConstruct
	private void initialize() {
		setDataSource(dataSource);
	}
	
}

Alternatively, create an own implementation of JdbcDaoSupport class, and do whatever you want. Dive inside the source code of JdbcDaoSupport, it’s just a simple helper class to create a jdbcTemplate.

Note
There is a jira report on Spring io, request to remove final modifiers, but the resolution is “won’t fix”.

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
mohammed ismail zabiulla
7 years ago

what to do if we have multiple dao and dao implementations? how to do datasource configuration in java. can u share that example please. awaiting for your valuable reply

???
7 years ago

Thanks for sharing ! It solves my problem.

Davy Claude
7 years ago

Thank you ! I couldn’t inject dataSource in my bean (property or constructor-arg)….

zygimantus
9 years ago

It was extremely helpful. Thanks for the solution.

MA Subhan
9 years ago

Thanks for sharing this information it was very helpful.

Regards
MA Subhan
http://www.upskilltechnologies.com