I’m a Spring newbie, I’m following some examples from books and tutorials in the spring website and I can’t get my code to work.
I’m trying to access to a DataBase using JdbcTemplate. This is how my root-context.xml looks like:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<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/db" />
<property name="username" value="userr" />
<property name="password" value="password" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource"/>
</bean>
<bean id="myDao" class="com.me.myproj.persistence.JdbcMyaDao">
<property name="dataSource" ref="dataSource"/>
</bean>
This is my JdbcMyDao (all imports are ok, I won’t paste them):
public class JdbcMyDao implements MyDao{
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public String getOpcionById(){
String SQL_Q="select name from options where id=35";
return (String)this.jdbcTemplate.queryForObject(SQL_Q, String.class);
}
}
Finally, my controller:
@Controller
public class myController {
@RequestMapping(value = "/show", method = RequestMethod.GET)
public String show(Model model){
JdbcMyDao daoP=new JdbcMyDao();
String op=daoP.getOpcionById();
model.addAttribute("op",op);
return "show";
}
}
Ok, then, show.jsp just prints the return string.
So, this is a very simple access to a DataBase, but I get a nullPointerException when using JdbcTemplate (in function getOpcionById)
I think this is because function setDataSource is never runned, I thought spring runs it by IoC, I tried to put @Autowired to jdbcTemplate property i JdbcMyDao, but it didn’t work either. Can someone tell me the steps Spring does and which steps should I do? Or what changes should I make and why?
Your controller is instantiating its own
JdbcMyDaoand calling that, rather than using the bean you declared inroot-context.xml. You need to inject themyDaobean into your controller and invoke that.Also, is there a reason you’re defining a
JdbcTemplatebean, and then not doing anything with it? ThesetDataSourcemethod of the DAO is instantiating its ownJdbcTemplate(which is fine), so there’s no reason to declare a bean.I have a feeling you’ve not quite grasped the concept of dependency injection – you seem to have used direct instantiation and declared beans, rather than just the latter.