Home  >  Q&A  >  body text

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 days ago558

reply all(2)I'll reply

  • 伊谢尔伦

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

    The basic concept is wrong. sgtPeppers() is a method of calling this class. If it is not defined, of course it will cause a compilation error and has nothing to do with spring.
    Change it like this:

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

    reply
    0
  • 阿神

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

    Incorrect understanding

    Can be used with @Bean @Qualifier

    reply
    0
  • Cancelreply