【问题标题】:Pre-defined beans in Spring BootSpring Boot 中的预定义 bean
【发布时间】:2016-03-25 21:10:57
【问题描述】:

我想创建一个基于 Spring Boot 的简单应用程序。我没有使用框架的经验,这个问题超出了我的范围。

我想在我的应用程序中使用安全模块,尤其是 org.springframework.security.authentication.encoding.ShaPasswordEncoder 类。我想把这个自动装配成一个 bean。

如何在 Spring Boot 中定义它?例如,this answer 解释了如何在“常规”Spring 中使用它——在 XML 文件中定义 bean。但是,当我阅读引导​​概述时,它指出不需要 XML 设置,那么是否有可能在代码中而不是配置中以某种方式做到这一点?什么是 Boot-ish 方式?

我已尝试仅使用此代码来获取编码器类。

@Autowired
private ShaPasswordEncoder passwordEncoder;

但是我得到了一个例外:org.springframework.beans.factory.NoSuchBeanDefinitionException -- 它没有定义,但是我该如何定义呢?

谢谢

【问题讨论】:

  • 我认为您仍然可以使用@Configuration 定义类和使用@Bean 定义方法。

标签: java spring spring-security spring-boot


【解决方案1】:

可以像这样在代码中定义 bean:

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

此方法将创建一个名为“passwordEncoder”的 bean,该 bean 将由 Spring 管理。它相当于 XML 样式的

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

您可以将此方法放在@SpringBootApplication-annotated 类中,或任何带有@Configuration 注释的类中。

More info here

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2019-08-10
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2020-08-15
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多