簡體   English   中英

SpringBoot無法找到Mongo存儲庫

[英]SpringBoot fails to find Mongo Repository

我在嘗試將第二個mongo數據庫添加到我的應用程序時遇到問題。 我通過添加第二個使用配置前綴然后使用特定bean名稱的MongoTemplate來實現。

我有一個像這樣的AbstractMongoConfig

public abstract class AbstractMongoConfig {
    private String uri;

    public void setUri(String uri) {
        this.uri = uri;
    }

    public MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClientURI(uri));
    }

    abstract public MongoTemplate getMongoTemplate() throws Exception;                                                                        }

我可以將其擴展到這樣的特定模板配置中...要添加另一個mongo DB,我將添加其中一個,然后通過templateRef注釋不同的存儲庫以使用不同的配置,對嗎?

@Configuration
@ConfigurationProperties(prefix="server.mongodb")
public class ServerMongoConfig extends AbstractMongoConfig {
    @Primary
    @Override
    @Bean(name="serverMongoTemplate")
    public MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

有了這個,我應該能夠像server.mongodb.uri = ...這樣的配置了。

我有一個使用此的回購

@Repository
public interface MAPRepository extends MongoRepository<MAP, String> {
    public List<MAP> findByName(String name);
}

和實體

@Document(collection="maptest")
public class MAP {
    @Id
    private String id;
    private String name;
}

然后,我有一個使用此倉庫的服務類

@EnableMongoRepositories(mongoTemplateRef="serverMongoTemplate")
@Service
public class TestService {
    @Autowired
    @Qualifier(value = "serverMongoTemplate")
    private MAPRepository mrepo;

    ... use mrepo ...
}

但是啟動時我收到一個錯誤

Description:

Field mrepo in testpkg.svc.TestHandler required a bean of type 'testpkg.repo.MAPRepository' that could not be found.

Action:

Consider defining a bean of type 'testpkg.repo.MAPRepository' in your configuration.

並降低...

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'testpkg.repo.MAPRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=serverMongoTemplate)}

該服務與存儲庫位於不同的程序包中,但是我已經檢查了導入以及所有這些內容……一切都很好。 MAPRepository帶有@Repository注釋,這意味着它應該作為Bean可用,對嗎?

還有什么可能導致這里看不到bean? 我可以打開一些類來了解發生什么情況嗎?

在添加ServerMongoConfig之前,它工作正常。 它能夠毫無問題地寫入該數據庫。 剛才它無法正確實例化它。

答案似乎是@EnableMongoRepositories需要具有一個basePackages,該basePackages引用包含新模板的正確軟件包,否則我猜mongoTemplateRef無法正確找到它。

因此,在服務類上:

@EnableMongoRepositories(basePackages={"testpkg.repo"}, mongoTemplateRef="serverMongoTemplate")

而且一切正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM