Java 弹簧:Can';t将字符串作为构造函数参数注入xml定义的bean
我试图将一个简单字符串作为构造函数arg注入扩展了Java 弹簧:Can';t将字符串作为构造函数参数注入xml定义的bean,java,spring,spring-security,Java,Spring,Spring Security,我试图将一个简单字符串作为构造函数arg注入扩展了org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint的bean中。这是一节课: @Component public class AuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { public AuthenticationEntry
org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint
的bean中。这是一节课:
@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");
}
}
在我的security-context.xml中,我对bean的定义如下:
<beans:bean id="authenticationEntryPoint" class="a.b.s.AuthenticationEntryPoint" >
<beans:constructor-arg index="0" type="java.lang.String" value="/login"/>
</beans:bean>
奇怪的是,它使用以下配置:
<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>
因此,只声明一个字符串bean而不使用它会使应用程序运行。有人能给我解释一下为什么会这样吗
L.E:我正在使用SpringContext 4.3.0和SpringSecurity 4.1.0
修复:
因为它是在xml中定义的,并且还带有@Component注释,所以Spring生成了两个相同类型的实例,所以当Spring在扫描包时试图调用构造函数,并且没有自动连接的字符串作为构造函数arg传递时,出现了错误。我通过简单地从AuthenticationEntry中删除@Component解决了这个问题点类
我们现在可以删除这篇文章了。这个问题是由您的
@Component
注释引起的,它是在组件扫描期间发现的,并且您没有为该bean定义提供字符串,导致容器配置失败
若要修复此问题,您必须删除其中一个配置,并且如果您决定保留基于注释的配置,还可以使用
@Value
注释插入字符串。它会隐藏一个错误。如果有两个相同bean的实例,那么如果标签id在bean中,如何为每个实例注入不同的字符串 我假设您已启用组件扫描?在本例中,首先获取@组件
-带注释的bean定义,尝试使用注释配置将@命名
,或@值
注入字符串。噢,我真傻,我在读你的注释时就明白了。因为它是用xml定义的,并且还用@Component
注释,所以Spring生成了两个相同类型的实例,所以当Spring在扫描包时试图调用构造函数,并且没有自动连接的字符串作为构造函数arg传递时,出现了错误。我通过简单地从AuthenticationEntryPoint
类中删除@组件来解决这个问题。谢谢@mszymborski如果你不介意的话,我将把它作为答案发布,这样它就不会污染“未回答”部分。
<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>