🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
因为按类型绑定可能会对于到多个合适的对象,所以在选择上要额外处理,一种方式就是用spring注解`@Primary`,当有多个可以绑定的对象时,选择此注解的bean, 如下,我们有`firstMovieCatalog` 作为主要的`MovieCatalog` ~~~java @Configuration public class MovieConfiguration { @Bean @Primary public MovieCatalog firstMovieCatalog() { ... } @Bean public MovieCatalog secondMovieCatalog() { ... } // ... } ~~~ 结合以上配置,下面的`MovieRecommender `会注入`firstMovieCatalog` ~~~java public class MovieRecommender { @Autowired private MovieCatalog movieCatalog; // ... } ~~~ 基于xml的配置,等同如下: ~~~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" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean class="example.SimpleMovieCatalog" primary="true"> <!-- inject any dependencies required by this bean --> </bean> <bean class="example.SimpleMovieCatalog"> <!-- inject any dependencies required by this bean --> </bean> <bean id="movieRecommender" class="example.MovieRecommender"/> </beans> ~~~