英文:
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 {
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论