Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

java - Spring Couldn't autowired,there is more than one bean of `` type

Here is my question:I have a base interface and two implementation class.

And a Service class has a dependencies on the base interface, the code is like this:

@Component
public interface BaseInterface {}

@Component
public class ClazzImplA implements  BaseInterface{}

@Component
public class ClazzImplB implements  BaseInterface{}

And the configuration is like this :

@Configuration
public class SpringConfig {
    @Bean
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}

The service class has dependencies on the base interface will decide to autowire which Implementation by some business logic.And the code is like this:


@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}

And the IDEA throws a exception:Could not autowire.There is more than one bean of BaseInterface type.

Although it can be solved by using @Qualifier,but in this situation I can't choose the dependencies class.

@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;

I tried to read the spring document and it provide a Constructor-based dependency injection but I'm still confused by the problem.

can anyone help me ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Spring is confused between the 2 beans you have declared in you configuration class so you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired, apply these modifications on your configuration class

@Configuration
public class SpringConfig {
    @Bean(name="clazzImplA")
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean(name="clazzImplB")
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}

then at @autowired annotation

@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    @Qualifier("the name of the desired bean")
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...