Java 如何以编程方式配置@ComponentScan?
我想找到以编程方式设置“@componentScan”的“basepackages”的方法 我有点像:Java 如何以编程方式配置@ComponentScan?,java,spring-mvc,Java,Spring Mvc,我想找到以编程方式设置“@componentScan”的“basepackages”的方法 我有点像: @Configuration @EnableWebMvc @ComponentScan(basePackages = "cl.pagefoo.controller") public class MyConfig extends WebMvcConfigurerAdapter{ ... } class foo extends Something{ void init(Somet
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "cl.pagefoo.controller")
public class MyConfig extends WebMvcConfigurerAdapter{
...
}
class foo extends Something{
void init(SomethingContext sc) throws Exception{
sc.setComponentScan("cl.pagefoo.controller");
}
}
我想要像这样的东西:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "cl.pagefoo.controller")
public class MyConfig extends WebMvcConfigurerAdapter{
...
}
class foo extends Something{
void init(SomethingContext sc) throws Exception{
sc.setComponentScan("cl.pagefoo.controller");
}
}
我想找到这个理论上的“something”类,它允许在运行时配置控制器包 您可以使用
WebApplicationInitializer
以编程方式创建应用程序上下文
public class Initializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.scan("com.package.name");
//the rest of initialization
}
}
这是配置web应用程序的另一种方法,因此您不再需要web.xml
更多阅读:
您有几个选择: .1。实际上,您可以指定占位符:
@ComponentScan(basePackages = "${mypackages}")
public class MyConfig {
...
}
但是,您必须尽早填充占位符值,最好是通过系统属性(-Dmypackages=somepackage
)来填充占位符值
.2。如果包名数量有限,可以尝试使用Spring概要文件
@ComponentScan(basePackages = "package1")
@Profile("profile1")
public class MyConfig1 {
...
}
@ComponentScan(basePackages = "package2")
@Profile("profile2")
public class MyConfig2 {
...
}
谢谢,你给了我很好的选择,我会去读的。