Spring框架-如何通过web表单修改服务属性



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

<<p> MyService接口/strong>
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>

不幸的是,在提交表单后,我给出了以下例外:

嵌套异常是beaninstantiationexception: Could not实例化bean类[com.webapp.service]。:指定的类一个接口有根本原因吗beaninstantiationexception: Could not实例化bean类[com.webapp.service]。:指定的类是一个接口

如果我写MyService类而不是MyService接口,问题就解决了。但是上面的代码只是示例。在我的实际情况中,我使用了该服务的许多实现,因此我需要使用接口。

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

一些例子:

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

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

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

现在运行正常:)

最新更新