我想將一個簡單的字符串作爲構造函數arg注入到一個擴展爲org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint
的bean中。這是類:春:無法將字符串注入xml定義的bean作爲構造函數arg
@Component
public class AuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public AuthenticationEntryPoint(String url) {
super(url);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
在我的安全-context.xml中,我定義我的豆如下:
<beans:bean id="authenticationEntryPoint" class="a.b.s.AuthenticationEntryPoint" >
<beans:constructor-arg index="0" type="java.lang.String" value="/login"/>
</beans:bean>
據我所知,這應該工作,但我得到以下錯誤:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationEntryPoint' defined in file [/a/b/c/d/target/app/WEB-INF/classes/a/b/s/AuthenticationEntryPoint.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type [java.lang.String] found for dependency [java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency [java.lang.String]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
奇怪的是,它適用於以下配置:
<beans:bean id="loginUrl" class="java.lang.String">
<beans:constructor-arg value="/login"/>
</beans:bean>
<beans:bean id="authenticationEntryPoint" class="a.b.s.AuthenticationEntryPoint" >
<beans:constructor-arg index="0" type="java.lang.String" value="/login"/>
</beans:bean>
所以,只聲明一個String bean而不使用它會使應用程序運行。有人可以向我解釋爲什麼會發生這種情況?
LE:我使用Spring上下文4.3.0和Spring 4.1.0安全
修復: 因爲它在XML定義,並與@Component註解,春天使同一類型的兩個實例,所以當Spring在掃描包的時候試圖調用構造函數並且它沒有自動裝配的字符串作爲構造函數arg傳遞時出現錯誤。我通過從AuthenticationEntry Point類中刪除@Component來解決它。
我們現在可以刪除這個帖子
我假設你已啓用組件掃描?在這種情況下,首先獲取具有@ Component註釋的bean定義,嘗試使用'@ Named'或'@ Value'使用註釋配置注入字符串。 – mszymborski
哦,愚蠢的我,當我讀到你的評論時,我發現了它。因爲它是在xml中定義的,並且也用'@ Component'註解,所以Spring創建了兩個相同類型的實例,所以當Spring在掃描包時嘗試調用構造函數並且沒有自動裝配的String作爲構造函數arg傳遞。我通過從AuthenticationEntryPoint類中刪除'@ Component'來解決它。謝謝@mszymborski –
如果你不介意我會發布這個答案,以便它不污染「未答覆」部分。 – mszymborski