我是Spring框架的新手。我打算用我的下一个项目使用两个gridfs模板。我想使用两个不同的数据库“ProductImage”和“ProfileImage”。根据用户上传的图像,应插入相关数据库中。所以我试图按如下方式配置我的application-context.xml
<!-- Mongo GridFs settings -->
<!-- Connection to MongoDB server -->
<mongo:db-factory host="192.168.1.3" port="27017"
dbname="ProfileImages" />
<mongo:mapping-converter id="converter"
db-factory-ref="mongoDbFactory" />
<!-- MongoDB GridFS Template -->
<beans:bean id="gridTemplate"
class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<beans:constructor-arg ref="mongoDbFactory" />
<beans:constructor-arg ref="converter" />
</beans:bean>
当我添加这个时,我的项目工作正常,但是当我添加
时<!-- Adding another mongo gridsfs -->
<!-- Connection to MongoDB server -->
<mongo:db-factory host="192.168.1.3" port="27017"
dbname="ProductImages" />
<mongo:mapping-converter id="ProductImages"
db-factory-ref="mongoDbFactory" />
<!-- MongoDB GridFS Template -->
<beans:bean id="gridTemplate1"
class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<beans:constructor-arg ref="mongoDbFactory" />
<beans:constructor-arg ref="ProductImages" />
</beans:bean>
我的程序抛出异常,如
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.data.mongodb.gridfs.GridFsOperations] is defined: expected single matching bean but found 2: [gridTemplate, gridTemplate1]
我缺少哪里?
答案 0 :(得分:1)
如果你正在使用@Autowired
注释并且有多个好的候选者(比如你添加了第二个定义bo GridFsTemplate),那么你需要使用另一个注释@Qualifier
。否则spring怎么会告诉你想要注入哪个gridfs实例?
样品:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
public class MyBean {
@Autowired @Qualifier("gridTemplate") private GridFsTemplate fs1;
@Autowired @Qualifier("gridTemplate1") private GridFsTemplate fs2;
}
编辑: 您还需要在xml配置中正确绑定bean(您有两个mongo:db-factory beans):
<!-- Mongo GridFs settings -->
<!-- Connection to MongoDB server -->
<mongo:db-factory host="192.168.1.3" port="27017"
id="profileImagesDbFactory"
dbname="ProfileImages" />
<mongo:mapping-converter id="profileImagesConverter"
db-factory-ref="profileImagesDbFactory" />
<!-- MongoDB GridFS Template -->
<beans:bean id="gridTemplate"
class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<beans:constructor-arg ref="profileImagesDbFactory" />
<beans:constructor-arg ref="profileImagesConverter" />
</beans:bean>
<!-- Adding another mongo gridsfs -->
<!-- Connection to MongoDB server -->
<mongo:db-factory host="192.168.1.3" port="27017"
id="productImagesDbFactory"
dbname="ProductImages" />
<mongo:mapping-converter id="ProductImages"
db-factory-ref="mongoDbFactory" />
<!-- MongoDB GridFS Template -->
<beans:bean id="gridTemplate1"
class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
<beans:constructor-arg ref="productImagesDbFactory" />
<beans:constructor-arg ref="ProductImages" />
</beans:bean>