开发者社区> 问答> 正文

Spring注入,在XML配置中引用JavaConfig,结果找不到Config中的bean 报错

"

XML:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--<bean id="sgtPeppers" class="com.soundsystem.SgtPeppers"/>-->
<!--引入JavaConfing配置类-->
<bean class="com.soundsystem.CDConfig"/>
<!--xml配置-->
<bean id="cdPlayer" class="com.soundsystem.CDPlayer">
    <constructor-arg ref="sgtPeppers"/>
</bean>

</beans>

sgtPeppers的bean配置在JavaConfig中:

package com.soundsystem;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CDConfig {
    @Bean
    public CompactDisc sgtPeppers(){
        return new SgtPeppers();
    }
}

执行后报错:
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cdPlayer' defined in class path resource [META-INF/spring/cdplayer-config.xml]: Cannot resolve reference to bean 'sgtPeppers' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sgtPeppers' available
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cdPlayer' defined in class path resource [META-INF/spring/cdplayer-config.xml]: Cannot resolve reference to bean 'sgtPeppers' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sgtPeppers' available

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sgtPeppers' available

IDEA显示是绿色的,但是为什么找不到

"

展开
收起
因为相信,所以看见。 2020-05-27 13:00:02 1399 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    "

    <bean id="cdPlayer" class="com.soundsystem.CDPlayer"> <constructor-arg ref="sgtPeppers"/> </bean> 意思是创建cdPlayer这个Bean的时候給CDPlayer的构造函数一个sgtPeppers对象
    ######

    开启注解
    <context:annotation-config />

    "

    2020-05-27 16:25:31
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载

相关实验场景

更多