我試圖通過spring java @Configuration
配置一堆庫。
在所有的頂部之一,我有一個Spring Web Mvc應用程序。Spring Web Mvc配置初始化
要配置應用程序,我使用了AbstractAnnotationConfigDispatcherServletInitializer
的擴展;從那裏我引用getRootConfigClasses()
方法中底層的另一個@Configuration
類,對於servlet容器,我使用getServletConfigClasses()
方法來引用WebMvcConfigurationSupport
的擴展。直到我需要從WebMvcConfigurationSupport
級別實例化的類的底層(攔截器,等等)中的一些bean;所有的作品都很好(Web MVC部分)。在這些類中,所有對應該在底層(使用@Component
註解的類)中初始化的beans的參考文件@Autowired
註釋給我null
。
在同一層堆棧(沒有MVC的服務層)之上的另一個應用程序中,所有工作都很好。
有什麼建議嗎?
EDIT
如果我加載從根配置類自動裝配作品豆(經由@Bean註釋)。
如果我從servlet(WebMvc)配置類自動裝配不起作用加載一個bean(通過@Bean註釋)。
看來他們是兩種不同的Spring環境。
一些代碼
攔截
package my.package.interceptor;
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {...}
根配置
package my.package;
@Configuration
@ComponentScan(
basePackageClasses={ UnderlyingLayersSpringConfiguration.class },
basePackages = {"my.package.interceptor"}
)
public class WebSpringConfiguration {...}
的MVC配置
package my.package;
@Configuration
@EnableWebMvc
@ComponentScan(
basePackageClasses = WebSpringConfiguration.class,
basePackages = {"my.package.interceptor"},
includeFilters = @Filter(Controller.class) ,
useDefaultFilters = false
)
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private AuthenticationInterceptor authenticationInterceptor;
}
的Web應用程序初始化:
2個版本版本1
package my.package;
public class WebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer
implements WebApplicationInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { WebSpringConfiguration.class, WebMvcConfig.class };
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
}
2版
package my.package;
public class WebAppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer
implements WebApplicationInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { WebSpringConfiguration.class };
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebMvcConfig.class };
}
}
錯誤
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [my.package.interceptor.AuthenticationInterceptor] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
其他類在相同的包支持autowire? – Priyamal