[英]How can Spring boot/Application.java pick up Mongo AbstractMongoConfiguration in another package?
I want to keep my classes organized into packages. 我想将我的班级整理成包。 Using the following example: 使用以下示例:
https://spring.io/guides/gs/accessing-data-mongodb/ https://spring.io/guides/gs/accessing-data-mongodb/
I have Application.java in "my.main.package" I define my own implementation of AbstractMongoConfiguration below: 我在“ my.main.package”中有Application.java,下面定义了我自己的AbstractMongoConfiguration实现:
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. 如果将类与Application.java放在同一包中,则它将起作用。 If I put MyMongoConfig in its own package ie "my.config.package.settings", then running Application.java appears to use the default MongoDB connection settings without using "MyMongoConfig". 如果我将MyMongoConfig放在其自己的包(即“ my.config.package.settings”)中,则运行Application.java似乎使用默认的MongoDB连接设置,而不使用“ MyMongoConfig”。 Why is my application not automatically finding the "MyMongoConfig" when its in a different package? 为什么我的应用程序位于其他软件包中时,为什么无法自动找到“ MyMongoConfig”? Is there a proper way or possibility to do this without shoving them both in the same package? 是否有适当的方法或可能性做到这一点而无需将它们都塞在同一个包装中?
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. 建议将主要的Spring Boot应用程序类放在其他类之上的根包中,以使基础“搜索包”成为根包。 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: 例如,如果您的主应用程序类位于软件包“ demo”中,而您的Mongo配置类位于软件包“ another.demo”中,则主应用程序类的@ComponentScan
批注应类似于:
@Configuration
@ComponentScan(basePackages={"another.demo", "demo"})
@EnableAutoConfiguration
public class Application {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.