Java Spring Autowiring 类与接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2387431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Autowiring class vs. interface?
提问by Marcus Leon
I have this Spring config:
我有这个 Spring 配置:
<bean id="boo" class="com.x.TheClass"/>
The class TheClass
implements TheInterface
. Then I have this (hypothetical) Java code:
该类TheClass
实现TheInterface
. 然后我有这个(假设的)Java 代码:
@Autowired
TheInterface x;
@Autowired
TheClass y;
The autowiring of TheInterface
works but the autowiring of TheClass
fails. Spring gives me a NoSuchBeanDefinitionException
for the class.
自动装配TheInterface
工作但自动装配TheClass
失败。春天给了我一个NoSuchBeanDefinitionException
班级。
Why can you wire the interface and not the class?
为什么你可以连接接口而不是类?
采纳答案by skaffman
Normally, both will work, you can autowire interfaces or classes.
通常,两者都可以工作,您可以自动装配接口或类。
There's probably an autoproxy generator somewhere in your context, which is wrapping your boo
bean in a generated proxy object. This proxy object will implement TheInterface
, but will not be a TheClass
. When using autoproxies, you need to program to the interface, not the implementation.
您的上下文中可能有boo
一个自动代理生成器,它将您的bean包装在生成的代理对象中。此代理对象将实现TheInterface
,但不会是TheClass
. 使用自动代理时,您需要对接口进行编程,而不是对实现进行编程。
The likely candidate is transactional proxies - are you using Spring transactions, using AspectJ or @Transactional
?
可能的候选对象是事务代理——您是使用 Spring 事务,使用 AspectJ 还是@Transactional
?