How can Spring boot/Application.java pick up Mongo AbstractMongoConfiguration in another package?

StackOverflow https://stackoverflow.com/questions/23210143

Pergunta

I want to keep my classes organized into packages. Using the following example:

https://spring.io/guides/gs/accessing-data-mongodb/

I have Application.java in "my.main.package" I define my own implementation of AbstractMongoConfiguration below:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

@Configuration
public class MyMongoConfig extends AbstractMongoConfiguration{
    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient("remotehost:27018");
    }

    @Override
    protected String getDatabaseName() {
        return "mydb";
    }
}

If I put the class within the same package as my Application.java, then it works. If I put MyMongoConfig in its own package i.e "my.config.package.settings", then running Application.java appears to use the default MongoDB connection settings without using "MyMongoConfig". Why is my application not automatically finding the "MyMongoConfig" when its in a different package? Is there a proper way or possibility to do this without shoving them both in the same package?

Foi útil?

Solução

It is recommended that the main Spring Boot application class to be located in a root package above other classes so that the base "search package" to be the root one. All packages from the root will be scanned for configuration classes.

If you choose to place some other configuration classes in other packages, I believe these needs to be specified. For example, if you have your main application class in package "demo" and your Mongo configuration class in package "another.demo", the @ComponentScan annotation for your main application class would need to look like:

@Configuration
@ComponentScan(basePackages={"another.demo", "demo"})
@EnableAutoConfiguration
public class Application {
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top