这个问题让我耗费了几天的时间。
问题描述:使用jpa向数据库存入数据,出错。
OperatorLogService operatorLogService=new OperatorLogService();
OperatorLog operatorLog=new OperatorLog();
operatorLog.setOperator(user.getUsername());
operatorLog.setContent("666666666666");
operatorLog.setCreateTime(new Date());
operatorLog.setUpdateTime(new Date());
operatorLogService.save(operatorLog);
代码如上所示,如果用new一个Service的方法,运行时在operatorLogService.save(operatorLog);这一句时运行会出错。
代码改成这样:
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
private UserService service;
@Autowired
private OperatorLogService operatorLogService;
@RequestMapping(value = "/test")
public String test(){
User user=new User();
user.setUsername("huangjingi");
user.setPassword("333333");
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
service.save(user);
OperatorLog operatorLog=new OperatorLog();
operatorLog.setOperator(user.getUsername());
operatorLog.setContent("666666666666");
operatorLog.setCreateTime(new Date());
operatorLog.setUpdateTime(new Date());
operatorLogService.save(operatorLog);
return "admin/test/test";
}
}
注意红色代码,Service对象只能用@Autowired方式注入,如果采用new的方式创建Service对象则运行时会出错。 |