SpringJDBC ClassPathXmlApplicationContext无法从资源中的xml加载getbean

时间:2017-05-20 09:42:51

标签: java spring-jdbc jdbctemplate

我是java中的菜鸟。我想将数据插入到employees表中。

  

错误:没有定义名为'employeeDAO.class'的bean。

     

我的代码结构:

enter image description here

这是我的代码。

  

file:com.vm.springjdbc.app.App.java

public class App {
    private ApplicationContext context;
    private EmployeeDAO employeeDAO;

    public static void main(String[] args) {
        context = new ClassPathXmlApplicationContext("Spring-Datasource.xml");
        employeeDAO = (EmployeeDAO) context.getBean("employeeDAO.class");
    }
}
  

file:com.vm.springjdbc.model.Employee.java

public class Employee { 
    private int id;
    private String name;
    private String mobile;
    setter & getter
}
  

file:com.vm.springjdbc.DAO.EmployeDAO.java

public class EmployeeDAO extends JdbcDaoSupport {   
    public void insert(Employee emp){       
    }
}
  

资源中的Xml文件:src / resources / Spring-Datasource.xml

<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-2.5.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/synapse4" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
    </bean>

    <bean id="employeeDAO" class="com.vm.springjdbc.DAO.EmployeeDAO">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>
  

请帮我解决一下

1 个答案:

答案 0 :(得分:1)

您应该将EmployeeDAO作为接口,并为此EmployeeDAOImpl创建一个impl类,如下所示:

  

EmployeeDAO.java

public interface EmployeeDAO 
{
    public void insert(Employee employee);
}
  

EmployeeDAOImpl.java

public class EmployeeDAOImpl extends JdbcDaoSupport implements EmployeeDAO
{
    public void insert(Employee employee){
        //insertion implementation
    }

}

并在Spring-Datasource.xml中进行以下更改

<bean id="employeeDAO" class="com.vm.springjdbc.DAO.EmployeeDAOImpl">
   <property name="dataSource" ref="dataSource" />
</bean>

另外,请不要在

中使用.class
employeeDAO = (EmployeeDAO) context.getBean("employeeDAO.class");

将其更改为

employeeDAO = (EmployeeDAO) context.getBean("employeeDAO");