【问题标题】:Spring Framework - how to modify service attribute via web formSpring Framework - 如何通过 Web 表单修改服务属性
【发布时间】: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


【解决方案1】:

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

一些例子:

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

【讨论】:

    【解决方案2】:

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

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

    现在它工作正常:)

    【讨论】:

      猜你喜欢
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 2018-12-29
      • 2020-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多