为什么我在这一行中有一个空点异常(状态=employeeDAO.saveEmployee(emp);



为什么我在这个行status=employeeDAO.saveEmployee(emp);中出现空点异常?

我正在尝试在 Spring 中使用 bean 和注释与数据库。

public class Main {
@Autowired
static EmployeeDAO employeeDAO;
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("config.xml");
Employee emp=(Employee) ac.getBean("emp");
emp.setId(2);
emp.setName("praful");
emp.setSalary(48000);
//EmployeeDAO employeeDAO=(EmployeeDAO) ac.getBean("edao");
int status=employeeDAO.saveEmployee(emp);  
System.out.println(status);  
}  
}
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />  
<property name="url" value="jdbc:mysql://localhost:3306/database1" />  
<property name="username" value="root" />  
<property name="password" value="123456" />  
</bean>  
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="ds"></property>  
</bean>  
<!--  
<bean id="edao" class="springWithDatabase.DAO.EmployeeDAO">  
<property name="jdbcTemplate" ref="jdbcTemplate"></property>  
</bean> 
-->   
<bean id="emp" class="springWithDatabase.Model.Employee">  
</bean>  
<context:component-scan base-package="springWithDatabase"/>
</beans>
@Service
public class EmployeeDAO {
private JdbcTemplate jdbcTemplate;  
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
this.jdbcTemplate = jdbcTemplate;  
}  
public int saveEmployee(Employee e){  
String query="insert into employee values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";  
return jdbcTemplate.update(query);  
}  
public int updateEmployee(Employee e){  
String query="update employee set name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
return jdbcTemplate.update(query);  
}  
public int deleteEmployee(Employee e){  
String query="delete from employee where id='"+e.getId()+"' ";  
return jdbcTemplate.update(query);  
}  
}
public class Employee {
private int id;  
private String name;  
private float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}  
}

你的 Main 类没有声明为 bean,因此它不是由 Spring 容器管理的,所以你不能在其中注入依赖关系。

使用ac.getBean("edao")从您的主方法获取您的员工DAO bean

最新更新