简体   繁体   中英

Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'

there are few answers to the question already. But none of them works for me.

I can't figure it out for the life of me why the error is coming.

Following are the approaches I tried:

  • using AbstractMongoConfiguration
  • Manually registering the mongoTemplate bean with ApplicationContext

Whenever I try to run my test during maven build or while deploying on tomcat error below comes up

Here is the configuration.

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:

@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;
}

}

Error log:

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

Get rid of the Profile("container") in MongoDBConfiguration .

Explanation: Because the @Profile is there, that means that that class will not be instantiated by Spring unless you are running Spring with that profile. My guess is that you are not setting spring.profiles.active property to "container" when you run your application via Tomcat or during your integration testing.

If you want to leave the @Profile("container") there then just make sure you set the profile to "container". There are multiple ways to do this. One quick easy way is to use Java system properties, eg -Dspring.profiles.active=container , when you execute your integration tests or run your application in Tomcat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM