我能结合 Spring @Profile 和 @Primary 注解在开发时强制选择 Bean 吗?

huangapple go评论54阅读模式
英文:

Can I combine Spring @Profile and @Primary annotations to force bean choice when doing development?

问题

I work on a team that uses lots of libraries that we have little control over.

One of them introduces a bean that I want to replace when running locally, using the "dev" profile. It implements the SuperClient interface.

It appears I can do this using the following, but is there a better way to do this?
Remember the constraints are that I don't have control over the other bean that is typically injected, so I can't add @Conditional annotations to it.
And I can't qualify every place it's injected, as I don't control much of that code either.

@Component
@Primary
@Profile("dev")
public class MyLocalDevelopmentOnlyReplacment implements SuperClient {
...
}

Note that I'd like to commit this class to our repo. to simplify local development for the entire team.

英文:

I work on a team that uses lots of libraries that we have little control over.

One of them introduces a bean that I want to replace when running locally, using the "dev" profile. It implements the SuperClient interface.

It appears I can do this using the following, but is there a better way to do this?
Remember the constraints are that I don't have control over the other bean that is typically injected, so I can't add @Conditional annotations to it.
And I can't qualify every place it's injected, as I don't control much of that code either.

@Component
@Primary
@Profile("dev")
public class MyLocalDevelopmentOnlyReplacment implements SuperClient {
...
}

Note that I'd like to commit this class to our repo. to simplify local development for the entire team.

答案1

得分: 0

我建议的方法似乎适用于我的用例,并且是我们现在在我们可以控制的代码中使用的。请注意,我还在调用的方法中添加了日志记录,记录类似以下内容的信息,并观察日志以查看是否显示(正如我希望的那样)

“仅限开发使用:如果在任何非生产环境或生产环境中找到,请将其记录为错误”

@Component
@Primary
@Profile("dev")
public class MyLocalDevelopmentOnlyReplacment implements SuperClient {
...
}
英文:

What I suggested seems to work fine for my use case, and is what we're using now in our code that we control. Note I added logging to the methods that are called as well that log something like the following, and watched the logs to see if this showed up, and it didn't (as I hoped)

"DEV ONLY usage: If found in any non-prod or prod environment, please log as a bug"

@Component
@Primary
@Profile("dev")
public class MyLocalDevelopmentOnlyReplacment implements SuperClient {
...
}

huangapple
  • 本文由 发表于 2023年5月17日 20:41:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定