问题描述
使用Spring Data Mongodb开发时,我想在MongoDB配置中进行一些自定义.通常,我将扩展AbstractMongoConfiguration,并实现抽象方法.当前, AbstractMongoConfiguration 类具有以下内容:
When developing with Spring Data Mongodb, I want to do some customization in my MongoDB configuraion.General, I will extends the AbstractMongoConfiguration, and implement the abstract methods. currently, the AbstractMongoConfiguration class has the following:
@Configuration
public abstract AbstractConfiguration extends MongoConfigurationSupport {
public abstract MongoClient mongoClient();
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactor(), mappingMongoConverter());
....
}
扩展此类时,我想自定义bean MongoTemplate ,所以我想重写 mongoTemplate 方法,这行得通吗?
When extending this class, I want to customize the bean MongoTemplate, So I want to override the mongoTemplate method, does this work?
@Configuration
public MongoConfiguration extends AbstractConfiguration {
public MongoClient mongoClient(){
....
}
@Override
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate template = super.mongoTemplate();
template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
}
....
}
推荐答案
最近有一个非常相似的问题.
Had an extremely similar issue recently.
有2种情况:
@Configuration
public MongoConfiguration extends AbstractConfiguration {
public MongoClient mongoClient(){
....
}
@Override
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate template = super.mongoTemplate();
template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
}
....
}
在这种情况下,将使用覆盖的定义而不是父定义来注册Bean.另外,只能注册1个豆.
In this case, the bean will be registered by using your overridden definition and not your parent definition. Also, only 1 bean will be registered.
@Configuration
public MongoConfiguration extends AbstractConfiguration {
public MongoClient mongoClient(){
....
}
@Override
@Bean(name="myBean")
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate template = super.mongoTemplate();
template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
}
....
}
在这种情况下,将创建 2个豆(mongoTemplate
和myBean
).但是,对于两个bean的创建,都将使用您覆盖的实现.
In this case, 2 beans(mongoTemplate
and myBean
) will be created. But, for the creation of both the beans, your overridden implementation will be used.
这篇关于如果我在Java配置中覆盖了bean定义,将会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!