Is it at all possible (or wise) to use a `typealia...
# spring
o
Is it at all possible (or wise) to use a
typealias
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:
Copy code
typealias SpringProfile = String

@Configuration
class SpringConfig {
  @Bean fun activeProfile(@Value("\${spring.profiles.active}") name: String): SpringProfile = name
}
s
Spring doesn’t know anything about the type alias, it’s just a String at runtime, like you said
👍🏻 1
👍 1
There are ways to have multiple beans share a type, though. For example you could look at the
@Qualifier
annotation.
o
Right. I was doing this to try and avoid using
@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.
s
I think you can also get away without using qualifiers in some cases when the name of the injected field matches the name of the bean, if that helps at all
t
but
spring.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)
or, instead of using spring native DI (
@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
Copy code
@Bean fun string() = "blah"
@Bean fun string2() = "blah"
you can do
Copy code
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 this
o
That's a good point about
spring.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! 👍
199 Views