Humberd Humberd - 1 month ago 17
Java Question

Spring - Mongo configuration class path

I have the following simple project structure:

enter image description here

Here are the implementation of these files:

Tryton - boot class

@SpringBootApplication
public class Tryton {
public static void main(String[] args) {
SpringApplication.run(Tryton.class, args);
}
}


UserRepository - Mongo Repository

public interface UserRepository extends MongoRepository<User, String> {
}


UserController - REST controller

@RestController
public class UserController {

private final UserRepository userRepository;

@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
}


MongoConfig

@Configuration
@EnableMongoRepositories
@ConfigurationProperties("foo")
class MongoConfig extends AbstractMongoConfiguration {

@Value("${mongodb.host}")
private String host;
@Value("${mongodb.port}")
private int port;
@Value("${mongodb.databaseName}")
private String databaseName;

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

@Override
public Mongo mongo() throws Exception {
return new Mongo(host, port);
}

}


It is very simple app: I inject
UserRepository
into
UserController
. Then I config MongoDB connection details in
MongoConfig
. Now everything works fine. But when I move
MongoConfig
into /configs package then the problem occurs:

enter image description here

And now the app can't start.

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.tryton.controllers.UserController required a bean of type 'com.tryton.repositories.UserRepository' that could not be found.


Action:

Consider defining a bean of type 'com.tryton.repositories.UserRepository' in your configuration.


Why does
MongoConfig
location change makes spring not able to recognise
UserRepository
as a
MongoRepository
?

dit dit
Answer

after moving to config package the default @EnableMongoRepositories target has been changed. Or more precisely, the base package has been changed to com.tryton.configs.*. Spring searching now for mongo repositories in this package.

you have now to add basePackages in @EnableMongoRepositories - annotation:

@Configuration
@EnableMongoRepositories(basePackages = {"com.tryton.repositories"})
@ConfigurationProperties("foo")
public class MongoConfig extends AbstractMongoConfiguration {
      [...]
}

Make sure your MongoConfig is public.