2015-08-12 4 views
0

Я использую Spring-Boot v1.3.0.M2. Я пытаюсь определить o.s.s.c.p.PasswordEncoder с помощью аннотаций. Мой класс конфигурации выглядит следующим образом. Этот пример отлично работает.Как определить PasswordEncoder с помощью аннотаций весной?

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
@Bean 
public PasswordEncoder getPasswordEncoder() { 
    return new StandardPasswordEncoder(); 
} 
} 

Однако, я хотел бы создать экземпляр StandardPasswordEncoder с секретом, и я пересмотрел свой класс следующим образом.

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
@Value(value="${password.secret}") 
private String secret; 

@Bean 
public PasswordEncoder getPasswordEncoder() { 
    return new StandardPasswordEncoder(secret); 
} 
} 

Обратите внимание, что мое приложение Spring-Boot выглядит следующим образом.

@SpringBootApplication 
@PropertySource("classpath:/config/myapp.properties") 
public class Application { 
public static void main(String[] args) { 
    SpringApplications.run(Application.class, args); 
} 

@Bean 
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholdConfigurer() { 
    return new PropertySourcesPlaceholderConfigurer(); 
} 
} 

И мой myapp.properties выглядит следующим образом.

password.secret=fsdkjfsldfsdfsdfsdf 

Когда я пытаюсь запустить приложение Spring-Boot, я получаю следующее исключение.


Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.crypto.password.PasswordEncoder]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getPasswordEncoder' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) 
    ... 102 more 

PasswordEncoder не может быть обработан, так как поле private String secret; не установлено, и, таким образом NullPointerException (NPE). Я попытался сделать метод getPasswordEncoder статическим, а также поле secret, но это не поможет.

Любые идеи о том, как я могу использовать аннотации, чтобы получить экземпляр PasswordEncoder с секретом?

ответ

0

Я нашел ответ, немного потрудившись. Я удалил поле secret и вместо этого просто аннотировал параметр следующим образом.

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

@Bean 
public PasswordEncoder getPasswordEncoder(@Value(value="${password.secret}") String secret) { 
    return new StandardPasswordEncoder(secret); 
} 
} 
+1

Он должен также работать с полем, я думаю, что аннотация Autowired была проблемой, так как вы не нужно, если у вас есть аннотация «Значение» в поле. – dunni

1

Bcrypt пароль шифратор, который Spring recommends над SHA или MD5, может быть сконфигурирован следующим образом:

@Bean 
public PasswordEncoder passwordEncoder() { 
    return new BCryptPasswordEncoder(); 
} 
Смежные вопросы