java - 将 Spring xml 配置 Controller 更新为注释

标签 java spring spring-mvc annotations

我的任务是更新一个不是我编写的旧项目。

该项目基于 Spring MVC,并且具有我不熟悉的旧 Spring Controller 配置。

Controller 的 bean 配置如下

<bean id="controllerName" class="the.project.controller.class">
<property name"serviceName">
  <ref bean="serviceName">
 </property>
<property name"successView">
  <value>viewName</value>
 </property>
</bean>

其中serviceName指的是用@Service注释的类,如下

  @Service(value=serviceName)

这是 xml 配置的正确替换吗?

@Autowired
@Qualifier("serviceName")
ServiceNameImpl serviceName

谢谢

这里编辑的是serviceName类和接口(interface)的组织

  public interface ServiceName {
   // methods omitted
 }

 @Service(value="serviceName")
 public class ServiceNameImpl implments ServiceName {
 //methods omitted
 }

@Resource 注释对我不可用(Spring 3.0.7)并且上面的 Autowire 失败(因为看起来类型不像下面描述的那样)

  org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching beans of type [the.project.ServiceNameImpl] found for dependency

鉴于编辑,我在这里做错了什么(抱歉遗漏了此信息)?

最后我需要能够访问接口(interface)的方法及其实现

例如

serviceName.doSomething(someVar);

最佳答案

这是正确的,但请考虑对 serviceName 使用 private 修饰符。另一种方法是使用@Resource:

@Resource
private ServiceNameClass serviceName;

请注意,在这种情况下,您不需要 @Qualifier("serviceName") - @Resource 按(字段)名称 Autowiring ,而 @Autowired 默认使用类型。只有当您有多个相同/兼容类型的 bean 时才会出现问题。

您还可以通过使用 @Controller 注释 Controller 类来完全跳过 controllerName bean 定义。

顺便说一句,您还可以使用以下语法稍微缩短 XML 配置:

<bean id="controllerName" class="the.project.controller.class">
    <property name"serviceName" ref="serviceName"/>
    <property name"successView" value="viewName"/>
</bean>

(IntelliJ 建议进行此转换并为您执行)。

关于java - 将 Spring xml 配置 Controller 更新为注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521530/

相关文章:

java - Android 中奇怪的数据绑定(bind)

java - 如何让我的 Java 代码接受使用自签名或弱 sslv2 协议(protocol)完成握手

java - .equals() 和 == 有什么区别?

java - Spring @RestController 是否默认启用 CORS?

hibernate - 在DAO,服务层架构中使用spring MVC和Hibernate的正确方法是什么

java - C++ 中的放置 new 运算符是什么,java 有吗?

java - android应用程序,客户端的sqlite或服务器端的memcached哪个更好,请说明原因

java - Spring在jsp中启用 Controller 页面渲染的问题

微软安全公告 ADV190023 的 Spring Ldap 影响(LDAP channel 绑定(bind)和 LDAP 签名)

java - 自定义页面登录表单以利用 spring 登录身份验证