Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

@Profile and overloading methods

 
Ranch Foreman
Posts: 1922
13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
According to the Spring 5 documentation section 1.13.1


With @Profile on @Bean methods, a special scenario may apply: In the case of overloaded @Bean methods of the same Java method name (analogous to constructor overloading), an @Profile condition needs to be consistently declared on all overloaded methods.
If the conditions are inconsistent, only the condition on the first declaration among the overloaded methods will matter.


If methods are overloaded, that means the methods return beans of the same type. The container does not know which bean to inject or autowire in this situation even if the active profile is set.
I think using @Primary on one of the bean methods can tell the container which bean to inject. The order of methods' declaration does not matter as the document describes.

Reference:
https://docs.spring.io/spring/docs/5.0.3.RELEASE/spring-framework-reference/core.html#beans-definition-profiles
 
Rancher
Posts: 1170
18
IntelliJ IDE Hibernate Firefox Browser MySQL Database Spring Tomcat Server Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you could use @Qualifier
 
Himai Minh
Ranch Foreman
Posts: 1922
13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I tried it.
I have two overloading methods annotated with @Bean. They have different @Profile. To my surprise, the second bean in the file is autowired, not the first one.
 
Tell me how it all turns out. Here is a tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic