我试图通过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