Spring - Mongo配置类路径

时间:2016-10-13 16:32:40

标签: java spring spring-data

我有以下简单的项目结构:

enter image description here

以下是这些文件的实现:

Tryton - 启动课程

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

UserRepository - Mongo存储库

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

UserController - REST控制器

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

}

这是一个非常简单的应用:我将UserRepository注入UserController。然后我在MongoConfig中配置MongoDB连接详细信息。现在一切正常。但是,当我将MongoConfig移到 / configs 包中时,会出现问题:

enter image description here

现在应用无法启动

***************************
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.

为什么MongoConfig位置更改导致Spring无法将UserRepository识别为MongoRepository

1 个答案:

答案 0 :(得分:3)

移动到配置包后,默认的@EnableMongoRepositories目标已更改。或者更确切地说,基础包已更改为com.tryton.configs.*。 Spring现在在这个包中搜索mongo存储库。

您现在要在@EnableMongoRepositories中添加 basePackages - 注释:

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

确保您的MongoConfig是公开的。