【问题标题】:Upgrading from spring 3.2 to spring 4.0 (NoSuchBeanDefinitionException)从 spring 3.2 升级到 spring 4.0 (NoSuchBeanDefinitionException)
【发布时间】:2015-10-28 13:25:41
【问题描述】:

我刚刚从 spring 3.2 更新到 spring 4.0.0.RC2 但现在我得到了以下期望

org.springframework.beans.factory.NoSuchBeanDefinitionException

运行测试时在我的 dao 类上。自动装配 PersistenceContext(这是我们自己的泛型类)时失败。

@Repository
public class AccountDaoImpl extends AbstractDao<Account> implements AccountDao {

    @Autowired
    public AccountDaoImpl(final PersistenceContext<Account> context) {
        super(context);
    }

...

如果我将版本改回 3.2,一切正常。导致此问题的 4.0 有何不同?

【问题讨论】:

  • 请发布完整的堆栈跟踪和PersistenceContext 的 bean 定义。

标签: spring


【解决方案1】:

这很可能是因为您要注入的 bean 是用不同的(而不是Account)类型参数声明的。 Spring Framework 4 现在执行更严格的类型检查。

这是一个说明问题的示例(SF 3.2.3.RELEASE 测试通过,4.0.0.RC2 测试失败):

@ContextConfiguration(classes=GenericAutowireTest.TestConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class GenericAutowireTest {

    public static class MyGenericClass<T> {
    }

    @Configuration
    public static class TestConfig {

        @Bean
        public MyGenericClass<String> myGenericClass() {
            return new MyGenericClass<String>();
        }
    }

    @Autowired 
    private MyGenericClass<Integer> myObject;

    @Test
    public void test() {
        assertNotNull(myObject);
    }

}

这里是a nice article,关于这项新功能。

解决方案是将“接受”@Autowired 字段类型分配给@Bean 返回类型,例如使它们相同,包括参数化类型。只有这样在运行时才有意义。

【讨论】:

  • 从本质上讲,我们通过单步执行 spring 代码使其工作。当获取泛型类型的 @Service bean 时,它会感到困惑。我很确定这是一个类型错误,就像你说的那样,它通过将泛型从类中移到另一个类中来解决。
  • @Smollet - 如果我想保留泛型类型,解决方案是什么?使用 @Qualifier("beanname") ?
  • @AndyDufresne 解决方案是在依赖注入的两侧创建相同的类型:@Bean 返回类型和“接受”@Autowired 字段类型(仅在运行时才有意义) .顺便提一句。当您使用 @Qualifier 注释时,倾向于使用一些通用概念来命名关系而不是 bean 名称(这也很好)。
  • @Smollet - 我没有遵循您的解决方案。我在这里详细说明了我的问题 - stackoverflow.com/questions/21473926/…。你有什么意见吗?
猜你喜欢
  • 1970-01-01
  • 2014-02-23
  • 1970-01-01
  • 1970-01-01
  • 2015-06-06
  • 2022-12-22
  • 2014-01-09
  • 2016-01-22
  • 2019-04-28
相关资源
最近更新 更多