Spring Autowiring 类与接口? [英] Spring Autowiring class vs. interface?

查看:25
本文介绍了Spring Autowiring 类与接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 Spring 配置:

I have this Spring config:

<bean id="boo" class="com.x.TheClass"/>

TheClass 类实现了 TheInterface.然后我有这个(假设的)Java 代码:

The class TheClass implements TheInterface. Then I have this (hypothetical) Java code:

@Autowired
TheInterface x;

@Autowired
TheClass y;

TheInterface 的自动装配有效,但 TheClass 的自动装配失败.Spring 为该类提供了一个 NoSuchBeanDefinitionException.

The autowiring of TheInterface works but the autowiring of TheClass fails. Spring gives me a NoSuchBeanDefinitionException for the class.

为什么你可以连接接口而不是类?

Why can you wire the interface and not the class?

推荐答案

通常,两者都可以工作,您可以自动装配接口或类.

Normally, both will work, you can autowire interfaces or classes.

您的上下文中可能有一个自动代理生成器,它将您的 boo bean 包装在生成的代理对象中.此代理对象将实现 TheInterface,但不会是 TheClass.使用自动代理时,您需要针对接口进行编程,而不是针对实现进行编程.

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.

可能的候选对象是事务代理——您使用的是 Spring 事务、AspectJ 还是 @Transactional?

The likely candidate is transactional proxies - are you using Spring transactions, using AspectJ or @Transactional?

这篇关于Spring Autowiring 类与接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆