设置 bean 属性“mongoOperations”时无法解析对 bean“mongoTemplate”的引用

问题描述 投票:0回答:2

这个问题的答案已经很少了。但它们都不适合我。

我一生都无法弄清楚为什么会出现错误。

以下是我尝试过的方法:

  • 使用 AbstractMongoConfiguration
  • 手动向 ApplicationContext 注册 mongoTemplate bean

每当我尝试在 Maven 构建期间或在 Tomcat 上部署时运行测试时,都会出现以下错误

这是配置。

package com.fordit.project.config;

@Configuration
@EnableMongoRepositories(basePackages = "com.company.project")
@ComponentScan(basePackages = "com.company.project")
public class ProjectConfiguration {

@Value("${project.db.driver_class}")
private String driverClassname;

@Value("${project.db.connection_string}")
private String connectionString;

@Bean
public DataSource dataSource() throws PropertyVetoException {
    Properties mysqlProperties = new Properties();
    mysqlProperties.setProperty("characterEncoding", "UTF-8");
    mysqlProperties.setProperty("useUnicode", "true");

    ComboPooledDataSource cpds = new ComboPooledDataSource();
    cpds.setProperties(mysqlProperties);
    cpds.setDriverClass(driverClassname);
    cpds.setJdbcUrl(connectionString);
    cpds.setAcquireIncrement(2);
    return cpds;
}

@Bean
public static PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() throws IOException {
    PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
    ResourceLoader resourceLoader = new PathMatchingResourcePatternResolver();
    ppc.setLocations(
            resourceLoader.getResource(System.getProperty("PROJECT_CONFIGURATION_FILE")));
    return ppc;
}

@Bean
public static RoleHierarchy roleHierarchy() {

    String roleHierarchyStringRepresentation
            = Role.ROLE_ADMIN + " > " + Role.ROLE_FIRM + "\n"
            + Role.ROLE_FIRM + " = " + Role.ROLE_LAWYER+ "= "+Role.ROLE_USER;

    //logger.info("Registered Role Hierarchy: \n{}", roleHierarchyStringRepresentation);
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    roleHierarchy.setHierarchy(roleHierarchyStringRepresentation);
    return roleHierarchy;
}
}

Mongo 配置:

@Configuration
@ComponentScan(basePackages = "com.company.project")
@Profile("container")
public class MongoDBConfiguration extends AbstractMongoConfiguration {

@Value("${project.mongodb.hostname}")
private String host;

@Value("${project.mongodb.port}")
private Integer port;

@Value("${project.mongodb.name}")
private String db;

@Value("${project.mongodb.username}")
private String username;

@Value("${project.mongodb.password}")
private String password;

@Value("${project.mongodb.authenticationDB}")
private String authDB;

@Bean
public MongoTemplate mongoTemplate()
    throws UnknownHostException, java.net.UnknownHostException {
return new MongoTemplate(
        new SimpleMongoDbFactory(
                    mongoClient(),
                    getDatabaseName()
            )
    );
}

@Override
@Bean
public MongoClient mongoClient()  {
    MongoClient mongoClient = null;
    try {
        mongoClient = new MongoClient(
                new ServerAddress(host, port),
                Collections.singletonList(
                        MongoCredential.createMongoCRCredential(
                                username,
                                authDB,
                                password.toCharArray()
                        )
                )
        );
    } catch (java.net.UnknownHostException ex) {
        Logger.getLogger(MongoDBConfiguration.class.getName()).log(Level.SEVERE, null, ex);
    }
    return mongoClient;
}

@Override
protected String getDatabaseName() {
    return db;
}

}

错误日志:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'forumDAL' defined in file [/home/ashay/projects/kuber/target/classes/com/fordit/kuber/forum/ForumDAL.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'forumRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:729)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:192)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1270)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1127)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:107)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:243)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117)
... 26 more
java mongodb spring-mvc spring-data
2个回答
2
投票

去掉

Profile("container")
中的
MongoDBConfiguration

说明:因为

@Profile
在那里,这意味着除非您使用该配置文件运行 Spring,否则 Spring 不会实例化该类。 我的猜测是,当您通过 Tomcat 运行应用程序或在集成测试期间,您没有将
spring.profiles.active
属性设置为“容器”。

如果您想将

@Profile("container")
保留在那里,请确保将配置文件设置为“容器”。 有多种方法可以做到这一点。 一种快速简单的方法是使用 Java 系统属性,例如
-Dspring.profiles.active=container
,当您在 Tomcat 中执行集成测试或运行应用程序时。


0
投票

mongo db 初学者。 我在一个 mongo 集合中有两个@Id。试图为多个自动生成的计数器建立一个集合。 删除了集合中的第二个@Id。

© www.soinside.com 2019 - 2024. All rights reserved.