为多个 spring 配置文件定义 bean
Defining beans per multiple spring profiles
我的应用程序中有 3 个配置文件:开发、测试、生产。
我想使用 spring 配置文件来自定义 bean 注入,这样对于配置文件开发和测试我将有一个 bean 实现,对于配置文件生产我将有另一个。
问题是如何实现这一目标。我如何设置一个 bean 在两个不同的配置文件中处于活动状态。
我试过这样的事情:
@Component
@Profile("dev, test")
class DevTestBean{}
但不幸的是 spring 将其视为一个名为 dev comma space test 的配置文件。
你得换成@Profile({"dev", "test"})
该值必须声明为 Set。
见 documentation
If a @Configuration class is marked with @Profile, all of the @Bean
methods and @Import annotations associated with that class will be
bypassed unless one or more of the specified profiles are active. This
is analogous to the behavior in Spring XML: if the profile attribute
of the beans element is supplied e.g., , the
beans element will not be parsed unless at least profile 'p1' or 'p2'
has been activated. Likewise, if a @Component or @Configuration class
is marked with @Profile({"p1", "p2"}), that class will not be
registered or processed unless at least profile 'p1' or 'p2' has been
activated.
XML官方文档中没有给出解决方法:
所以为了记录,我会把它放在这里:
<beans profile="dev,foo,bar">
<!-- (...) -->
</beans>
我的应用程序中有 3 个配置文件:开发、测试、生产。 我想使用 spring 配置文件来自定义 bean 注入,这样对于配置文件开发和测试我将有一个 bean 实现,对于配置文件生产我将有另一个。 问题是如何实现这一目标。我如何设置一个 bean 在两个不同的配置文件中处于活动状态。 我试过这样的事情:
@Component
@Profile("dev, test")
class DevTestBean{}
但不幸的是 spring 将其视为一个名为 dev comma space test 的配置文件。
你得换成@Profile({"dev", "test"})
该值必须声明为 Set。 见 documentation
If a @Configuration class is marked with @Profile, all of the @Bean methods and @Import annotations associated with that class will be bypassed unless one or more of the specified profiles are active. This is analogous to the behavior in Spring XML: if the profile attribute of the beans element is supplied e.g., , the beans element will not be parsed unless at least profile 'p1' or 'p2' has been activated. Likewise, if a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class will not be registered or processed unless at least profile 'p1' or 'p2' has been activated.
XML官方文档中没有给出解决方法:
所以为了记录,我会把它放在这里:
<beans profile="dev,foo,bar">
<!-- (...) -->
</beans>