无法将mongoDB主机设置为MongoRepository

时间:2016-10-01 22:11:30

标签: spring spring-data

我有以下用户结构:

@Document
public class User {
    @Id
    private String _id;
    private String role;
    private String username;
}

和mongo 存储库接口:

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

我将以下配置放在 XML 文件中:

<mongo:mongo host="www.example.com" port="12345"/>

<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongo"/>
    <constructor-arg name="databaseName" value="geospatial"/>
</bean>

现在我尝试保存用户:

@Autowired
private UserRepository userRepository;

public void foo() {
    User newUser = new User();
    newUser.setUsername("Humberd");
    newUser.setRole("USER");
    userRepository.insert(newUser);
}

尽管将主机设置为&#34; www.example.com&#34; spring仍然连接到我的localhost:

org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:42}] to localhost:27017

我做错了什么?如何将主机设置为自定义主机?

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情:

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

    private String host = "myhost";
    private int port = 12345;
    private String databaseName = "fooDB";

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

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

}