0

I want to create a simple app built on Spring Boot. I don't have experience with the framework, and this issue is beyond me.

I want to use the Security module in my app, particularly the org.springframework.security.authentication.encoding.ShaPasswordEncoder class. I want to get this autowired as a bean.

How do I define that in Spring Boot? For instance, this answer explains how to use it in "regular" Spring - defining the bean in a XML file. However, when I was reading the Boot overview, it stated that there is no need for XML setup, so is it possible to somehow do this in code, not configuration? What is the Boot-ish way?

I have tried just using this code to get the encoder class.

@Autowired
private ShaPasswordEncoder passwordEncoder;

But I get an exception: org.springframework.beans.factory.NoSuchBeanDefinitionException -- it's not defined, but how do I define it?

Thanks

Community
  • 1
  • 1
Martin Melka
  • 7,177
  • 16
  • 79
  • 138

1 Answers1

2

The beans can be defined in-code like this:

@Bean
public ShaPasswordEncoder passwordEncoder() {
    return new ShaPasswordEncoder();
}

This method will create a bean named "passwordEncoder" which will be managed by Spring. It is the equivalent of the XML-styled

<bean class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" id="passwordEncoder" />

You can put this method in the @SpringBootApplication-annotated class, or any class annotated with @Configuration.

More info here

Martin Melka
  • 7,177
  • 16
  • 79
  • 138