非常简单的场景:我正在使用 Spring 和 Spring Security,并且我试图将一个属性注入(inject)到我的 AuthenticationManager 使用的 AuthenticationProvider 中。我只是想我也许可以将其连接到 applicationContext 中,但不确定这是否可行。
applicationContext.xml:
<http use-expressions="true">
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/**" access="hasRole('USER')"/>
<form-login login-page="/index" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider ref="twitterAuthenticationProvider" />
</authentication-manager>
<beans:bean id="twitterAuthenticationProvider" class="com.bottlingday.model.auth.TwitterAuthenticationProvider" />
TwitterAuthenticationProvider:
public class TwitterAuthenticationProvider implements AuthenticationProvider
{
@Autowired
private AppEngineUserStore userStore;
static Log log = LogFactory.getLog(TwitterAuthenticationProvider.class.getName());
public void Test()
{
//userStore is always null here
log.info("test");
}
}
在我的 Controller 中,这失败了,因为 userStore 是 TwitterAuthenticationProvider 中的空引用:
Authentication authentication = this.authenticationManager.authenticate(authToken);
这是确切的错误:
java.lang.NullPointerException
at com.bottlingday.model.auth.TwitterAuthenticationProvider.authenticate(TwitterAuthenticationProvider.java:33)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:156)
at com.bottlingday.auth.TwitterAuthController.OauthCallback(TwitterAuthController.java:129)
编辑:我正在使用 Autowiring ,它对于其他事情来说效果很好。如果我在 MVC Controller 中 Autowiring AppEngineUserStore,它每次都会在那里。
最佳答案
I just had the thought that I might be able to wire it up in the applicationContext, but not sure if that would work.
这会起作用。您可以在应用程序上下文中指定属性的连接。
但是,这与 Autowiring 不同(这是您的 AuthenticationProvider
中的 Autowiring 。
如果您希望 Autowiring AppEngineUserStore,则需要在应用程序上下文中注册它并打开 Autowiring 。这可以按如下方式完成:
<context:annotation-config />
Spring 还可以扫描 bean 来 Autowiring ,如果您使用:
<context:component-scan base-package="com.my.package" />
这将自动打开 Autowiring
关于java - 如何将属性注入(inject)到未实例化的对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980939/