Spring Framework - 如何通过Web表单修改服务属性

时间:2014-07-31 14:57:27

标签: java spring spring-mvc thymeleaf

我使用Spring 4和Thymeleaf来构建我的应用程序。我需要在会话中存储一些数据,所以我决定创建一个会话服务。现在我想通过Web表单修改服务attibutes。我试着这样做:

MyService界面

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接口,问题就会解决。但上面的代码只是样本。在我的实际情况中,我使用了许多服务实现,因此我需要使用接口。

2 个答案:

答案 0 :(得分:0)

您无法创建界面实例,这就是它抛出异常的原因。当spring尝试为每个bean声明调用工厂方法时,它会失败,因为你声明了接口而不是它的实现。

一些例子:

<bean id= "myServiceImpl" class="some.package.MyServiceImpl"/>

答案 1 :(得分:0)

问题解决了。我将postAction方法修改为以下形式:

public String postAction(WebRequest webRequest) {
    WebRequestDataBinder binder = new WebRequestDataBinder(service, "service");
    binder.bind(webRequest);
    return "redirect:/my_test_action";
}

现在工作正常:))