2013-03-19 3 views
0
автоматического связывания

мою Spring.xmlSpring DataSource боб не должным образом

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" 
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:util="http://www.springframework.org/schema/util" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
    http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
<context:annotation-config /> 
<context:component-scan base-package="org.test.dao.impl"></context:component-scan> 

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver.class"></property> 
    <property name="url" value="jdbc:oracle:thin:@//localhost:1521/XE"></property> 
    <property name="username" value="test"></property> 
    <property name="password" value="testpass"></property> 
</bean> 

моя модель

package org.test.model; 

public class User { 

private String id; 
private String name; 
private String password; 
public String getId() { 
    return id; 
} 
public void setId(String id) { 
    this.id = id; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public String getPassword() { 
    return password; 
} 
public void setPassword(String password) { 
    this.password = password; 
} 

}

мой дао

package org.test.dao; 

import org.test.model.User; 
import java.util.List; 
public interface TestInterface { 
public List<User> getAllUsers(); 
} 

мой DaoImplementation

package org.test.dao.impl; 

import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List; 

import javax.sql.DataSource; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Required; 
import org.springframework.jdbc.core.JdbcTemplate; 
import org.springframework.jdbc.core.RowMapper; 
import org.springframework.jdbc.core.support.JdbcDaoSupport; 
import org.springframework.stereotype.Component; 
import org.test.dao.TestInterface; 
import org.test.model.User; 
@Component 
public class TestInterfaceImpl implements TestInterface { 

public DataSource dataSource; 
private JdbcTemplate jdbcTemplate; 
public DataSource getDataSource() { 
    return dataSource; 
} 
@Autowired 
public void setDataSource(DataSource dataSource) { 
    this.dataSource = dataSource; 
    System.out.println(dataSource); 
} 
@Override 
public List<User> getAllUsers() { 
      jdbcTemplate = new JdbcTemplate(); 
      jdbcTemplate.setDataSource(getDataSource()); 
      String sql = "SELECT * FROM TEST_USERS"; 
      return jdbcTemplate.query(sql, new UserRowMapper()); 
} 
private class UserRowMapper implements RowMapper<User>{ 

    @Override 
    public User mapRow(ResultSet rs, int num) throws SQLException { 
     User user = new User(); 
     user.setId(rs.getString("ID")); 
     user.setName(rs.getString("NAME")); 
     user.setPassword(rs.getString("PASSWORD")); 
     return user; 
    } 

} 

} 

мой основной класс

package org.test.run; 

import java.util.List; 

import org.test.dao.impl.TestInterfaceImpl; 
import org.test.model.User; 

public class Run { 

/** 
* @param args 
*/ 
public static void main(String[] args) { 
    TestInterfaceImpl t = new TestInterfaceImpl(); 
    List<User> users = t.getAllUsers(); 
    System.out.println(users); 
} 

} 

ОШИБКА Я получаю

Exception in thread "main" java.lang.IllegalArgumentException: No DataSource specified 
at org.springframework.util.Assert.notNull(Assert.java:112) 
at  o  `enter code here`rg.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:99 ) 
at `enter code here`org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79) 
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:381) 
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:455) 
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:463) 
at org.test.dao.impl.TestInterfaceImpl.getAllUsers(TestInterfaceImpl.java:35) 
at org.test.run.Run.main(Run.java:15) 

Всякий раз, когда я пытаюсь внедрить источник данных, он не работает. Я не знаю, что пошло не так. вся конфигурация на месте. Пожалуйста помоги.

Заранее спасибо.

+0

Ваш db-адрес не выглядит правильным, должен быть 'jdbc: oracle: thin: @localhost: 1521: XE', ваш выглядит как комбинация oracle и mysql, также обычно имя драйвера -' oracle.jdbc. driver.OracleDriver' без 'class' – Dreamer

+0

Попробуйте добавить' @Qualifier («myDataSource») 'в метод set @ @ AutoWired'. – Bart

ответ

0

дао класс реализации должен быть помечен для обработки весной:

@Repository 
public class TestInterfaceImpl implements TestInterface {} 

Теперь, если сканирование весной пакета используется, он будет найти этот класс и процесс всех @Autowired аннотаций.

Хотя это необязательно, но попробуйте добавить @Qualifier аннотацию к вашему методу настройки источника данных.

@Autowired 
@Qualifier("myDataSource") 
public void setDataSource(DataSource dataSource) { 
    this.dataSource = dataSource; 
    System.out.println(dataSource); 
} 

Комментирование вашего DAO класса @Repository будет решать вопросы. Вы можете предоставить идентификатор вашему классу dao, сделав аннотацию @Repository("testInterfaceImpl").

+0

Я пробовал это, но все же выбрасывает исключение нулевого указателя. – user2182000

Смежные вопросы