在Spring Boot中放置@Bean的位置? [英] Where to put @Bean in Spring Boot?

查看:208
本文介绍了在Spring Boot中放置@Bean的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Spring Boot应用程序注册其他bean的最佳位置是什么。我有一个使用 @SpringBootApplication 注释的Main类,并且拾取了该类中定义的bean。但是当我把那些豆子放在另一个班级时,它似乎没有被注册。

I am wondering what the best place would be for a Spring Boot app to register additional beans. I have a Main class that is annotated with @SpringBootApplication and beans defined in that class are picked up. But when i put those beans in another class it seems that the are not being registered.

在阅读文档时我明白了 @ SpringBootApplication 将隐式搜索其中包含 @Bean 注释的类。

When reading the documentation i got the idea that the @SpringBootApplication would implicitly search for classes that have @Bean annotations in them.

所以我的选择现在是:


  1. 将所有 @Bean 带注释的bean放入我的主要课程

  1. Put all @Bean annotated bean in my main class

@SpringBootApplication
public class MyApplication {

    @Bean
    public Filter AuthenticationFilter() {
        return new AuthenticationFilter();
    }

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}


  • 创建配置类并使用 @Configuration

    @Configuration
    public class MyConfiguration {
        @Bean
        public Filter AuthenticationFilter() {
            return new AuthenticationFilter();
        }
    }
    


  • 有没有更好的方法呢?

    推荐答案

    这几乎是一个偏好问题,但它通常被认为是最好的练习将暴露的bean放在逻辑上分组的配置类中。

    It is pretty much a matter of preference, but it is generally considered best practice to put exposed beans in configuration classes, which are logically grouped.

    例如,您可能有几个配置类,其中包含多个bean:身份验证配置用于AuthenticationProvider或UserDetailsS​​ervice的bean的类;一个Thymeleaf配置类,包含各种Thymeleaf方言等的bean。

    For example, you might have several configuration classes with a number of beans contained within each: An authentication configuration class with beans for AuthenticationProvider or UserDetailsService; a Thymeleaf configuration class containing beans for various Thymeleaf dialects, etc.

    这篇关于在Spring Boot中放置@Bean的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆