【发布时间】:2014-07-31 14:57:26
【问题描述】:
我使用 Spring 4 和 Thymeleaf 来构建我的应用程序。我需要在会话中存储一些数据,所以我决定创建一个会话服务。现在我想通过网络表单修改服务属性。我试着这样做:
我的服务界面
public interface MyService {
String getTitle();
void setTitle(String title);
}
MyService 实施
@Service
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class MyServiceImpl implements MyService {
private String title;
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
}
控制器类
@Controller
public class MyController {
@Autowired
private MyService service;
@RequestMapping(value = "my_test_action", method = RequestMethod.GET)
public String getAction(Model model) {
model.addAttribute("service", service);
return "my_view";
}
@RequestMapping(value = "my_test_action", method = RequestMethod.POST)
public String postAction(MyService service) {
return "my_view";
}
}
观点
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<form th:object="${service}" th:action="@{'/my_test_action'}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<input th:name="title" th:value="*{title}"/>
<input type="submit" />
</form>
</body>
</html>
提交表单后不幸的是,我给出了以下异常:
嵌套异常是 org.springframework.beans.BeanInstantiationException:不能 实例化 bean 类 [com.webapp.service.MyService]:指定类 是一个接口] 有根本原因 org.springframework.beans.BeanInstantiationException:不能 实例化 bean 类 [com.webapp.service.MyService]:指定类 是一个接口
如果我写的是 MyService 类而不是 MyService 接口,问题就会得到解决。但上面的代码只是示例。在我的真实案例中,我使用了许多服务实现,因此我需要使用接口。
【问题讨论】:
-
MyService 和 MyServiceImpl 在同一个包中吗?你也可以分享dispatcher-servlet.xml中使用
component-scan的部分吗? -
@Aditya Jain:是的,MyService 和 MyServiceImpl 位于同一个包中。通常我的应用程序工作正常。提交表单后抛出异常。
-
由于您有可用的接口,请尝试使用
ScopedProxyMode.INTERFACES而不是ScopedProxyMode.TARGET_CLASS -
@Aditya Jain:问题尚未解决,但您可能是对的。我使用接口,所以我应该使用 ScopedProxyMode.INTERFACES,谢谢。
-
你如何引导 spring ?周围有任何
Configuration或xml 吗?
标签: java spring spring-mvc thymeleaf