What happens in Spring if I use the @ActiveProfiles annotation on a configuration class instead use it on the class that defines my beans?

做~自己de王妃 提交于 2019-12-04 03:35:51

If you look at the JavaDoc of ActiveProfiles annotation, it contains this text:

ActiveProfiles is a class-level annotation that is used to declare which active bean definition profiles should be used when loading an ApplicationContext for test classes.

Meaning it is only supposed to be used to declare active Spring profiles for test classes. So If put it on a Configuration class it should have no effect.

And as for the @Profile annotation, it can be used on both method and class level. If you use it on method annotated with @Bean in configuration class, only that bean will belong to the profile. If you use it on configuration class, it will be applied to all the beans within the configuration class, if you use it on @Component class, the profile will be applied to the bean represented by that class.

@Profile annotation JavaDoc provides more detailed explanation of these rules.

Why I have to use the @Profile annotation on a **configuration class* instead annotate directly my beans?

Well if all beans in given configuration class should be active only for certain profile(s) then it makes sense to declare that globally on the configuration class to avoid having to individually specify the profile on all beans. But If you were to annotate all indiviudal beans it would work as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!