生活随笔
收集整理的這篇文章主要介紹了
避免不必要的Spring配置组件扫描
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我在堆棧溢出中遇到了一個有趣的問題。 Brett Ryan有問題,Spring Security配置被初始化了兩次。 當我查看他的代碼時,我發現了問題所在。 讓我展示顯示代碼。
他有相當標準的Spring應用程序(不使用Spring Boot)。 使用基于Spring的AbstractAnnotationConfigDispatcherServletInitializer更現代的Java servlet配置。
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class AppInitializer extendsAbstractAnnotationConfigDispatcherServletInitializer {@Overrideprotected Class<?>[] getRootConfigClasses() {return new Class[]{SecurityConfig.class};}@Overrideprotected Class<?>[] getServletConfigClasses() {return new Class[]{WebConfig.class};}@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}}
如您所見,有兩個配置類:
- SecurityConfig –保存Spring Security配置
- WebConfig – Spring的主要IoC容器配置
package net.lkrnac.blog.dontscanconfigurations;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {System.out.println("Spring Security init...");auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");}}import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "net.lkrnac.blog.dontscanconfigurations")
public class WebConfig extends WebMvcConfigurerAdapter {}
注意WebConfig的組件掃描。 這是掃描軟件包,所有三個類都位于該軟件包中。 在servlet容器上運行此命令時,將文本“ Spring Security init…”寫入控制臺兩次。 這意味著SecurityConfig配置被加載兩次。 它已加載:
在方法AppInitializer.getRootConfigClasses()的Servlet容器初始化期間 通過類WebConfig組件掃描 為什么? 我在Spring的文檔中找到了這種解釋 :
請記住, @Configuration類使用@Component進行元注釋 ,因此它們是組件掃描的候選對象!
因此,這是Spring的功能,因此我們要避免Servlet配置使用的Spring @Configuration組件掃描。 Brett Ryan獨立地發現了這個問題,并在提到的Stack Overflow問題中展示了他的解決方案:
@ComponentScan(basePackages = "com.acme.app",excludeFilters = {@Filter(type = ASSIGNABLE_TYPE,value = {WebConfig.class,SecurityConfig.class})})
我不喜歡這種解決方案。 注釋對我來說太冗長了。 另外,一些開發人員可以創建新的@Configuration類,而忘記將其包含在此過濾器中。 我寧愿指定將被Spring的組件掃描排除的特殊軟件包。
- 我在Github上創建了示例項目,以便您可以使用它。
翻譯自: https://www.javacodegeeks.com/2014/12/avoid-unwanted-component-scanning-of-spring-configuration.html
總結
以上是生活随笔為你收集整理的避免不必要的Spring配置组件扫描的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。