我的任务是更新一个不是我编写的旧项目。
该项目基于 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/