Heim  >  Fragen und Antworten  >  Hauptteil

java - 为什么@Import引入一个config不能使用这个config中@Bean注解的方法?

@Configuration
public class CDPlayerConfig {

    @Bean
    public CompactDisc sgtPeppers(){
        return new SgtPeppers();
    }
    
    @Bean
    public CDPlayer cdPlay(){
        return new CDPlayer(sgtPeppers());
    }

}

这个是能执行的

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

放到另一个配置文件中,然后通过@Import引入

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

引入外部的配置文件

@Configuration
@Import(CDConfig.class)
public class CDPlayerConfig {
 @Bean
    public CDPlayer cdPlay(){
        return new CDPlayer(sgtPeppers());
    }
}

就找不到这个method

巴扎黑巴扎黑2744 Tage vor561

Antworte allen(2)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:51:33

    基本概念错误,sgtPeppers()是调用本类的方法,没有定义当然编译错误,和spring无关。
    这么改:

    @Configuration
    @Import(CDConfig.class)
    public class CDPlayerConfig {
     @Bean
        public CDPlayer cdPlay(CompactDisc cd){
            return new CDPlayer(cd);
        }
    }

    Antwort
    0
  • 阿神

    阿神2017-04-18 10:51:33

    理解有误

    可以使用 @Bean @Qualifier配合

    Antwort
    0
  • StornierenAntwort