orrc
12/15/2022, 12:46 PMtypealias
as the return type of a @Bean
?
I just tried this, but it basically turns up as an unqualified java.lang.String
, i.e. if there's another @Bean
returning a String
, they're in conflict:
typealias SpringProfile = String
@Configuration
class SpringConfig {
@Bean fun activeProfile(@Value("\${spring.profiles.active}") name: String): SpringProfile = name
}
Sam
12/15/2022, 12:50 PMSam
12/15/2022, 12:50 PM@Qualifier
annotation.orrc
12/15/2022, 12:54 PM@Qualifier
and so be able to just have profile: SpringProfile
be injected in a service, without having to annotate it.
I also just now tried making SpringProfile
a value class
but since that also compiles down to a String, it had the same problem.
I just wrapped the value in a data class
now and have the desired effect.Sam
12/15/2022, 12:58 PMthanksforallthefish
12/15/2022, 12:59 PMspring.profiles.active
can be a list though, so what you are doing is smelly to me.
as an alternative, instead of a bean, you could also have an extension method on org.springframework.core.env.Environment
and inject environment directly (so you can have more complex/reliable logic on how to go from a list of profiles to a single one)thanksforallthefish
12/15/2022, 1:04 PM@Autowired
) you can use @javax.annotation.Resource
: autowired injects by type first, so with 2 beans of the same type you have to solve the conflict manually (changing the types, or using @Qualifier
). @Resource
I think it injects first by name, so if you have
@Bean fun string() = "blah"
@Bean fun string2() = "blah"
you can do
class Something(@Resource string: String, @Resource string2: String)
disclaimer: I think, anyway it looks very hacky to me so I prefer @Qualifier
and am not 100% sure it really behaves like thisorrc
12/15/2022, 2:48 PMspring.profiles.active
being a list. Though I believe in 100% of our cases it's a single item, which reflects the environment name.
But yeah, since the use case here is to basically inject an indicator of which environment the service is running in, it does suggest that potentially there's a better way of doing it.
Indeed, I just tried adding an extension property to Environment
, and that works well without needing any stringly-typed @Value
annotations, or any other configuration.
Thanks! 👍