I need to expose a method as a bean in Spring% with% to use it in the injection of an attribute, which has more than one implementation. What I did was the following:
I added the method that will create my object using the ApplicationContext
annotation:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public CsrfTokenRepository csrfTokenRepository() {
return CookieCsrfTokenRepository.withHttpOnlyFalse();
}
[...]
}
I added @Bean
to inject the attribute that has the type of interface @Autowired
that is returned by the method I exposed as Spring bean:
public final class RestClient<T> {
private Class<T> type;
@Autowired
private CsrfTokenRepository csrfTokenRepository;
[...]
}
When I try to use the attribute, NPE occurs because it was not injected by Spring:
public final class RestClient<T> {
private Class<T> type;
@Autowired
private CsrfTokenRepository csrfTokenRepository;
public HttpHeaders csrfHeaders() throws IOException {
CsrfToken csrfToken = csrfTokenRepository.generateToken(null); //Aqui ocorre o NPE!
HttpHeaders headers = createHeaders();
headers.add(csrfToken.getHeaderName(), csrfToken.getToken());
headers.add("Cookie", "XSRF-TOKEN=" + csrfToken.getToken());
return headers;
}
}
java.lang.NullPointerException at br.com.restclientjersey.RestClient.csrfHeaders (RestClient.java:61) at br.com.restclientjersey.RestClient.postCall (RestClient.java:47) at br.com.restclientjersey.RestClientTest.testPostCallStatus200 (RestClientTest.java:83)
The attribute is still not injected. I even tried to add CsrfTokenRepository
but it still does not work. What is missing to be able to inject this attribute by calling the Qualifier
method?