英文:
Is it a good practice to have POJO settings class as a bean?
问题
- 每次调用需要它的方法时创建这个POJO。
- 将其设置为单例bean,创建一次,然后自动装配它。
英文:
I have a simple POJO class with few fields. This POJO serves the role of settings and it is passed to one method which actually executes some logic. Fields from this POJO are taken from the app.properties and they will not change.
What is a better pratice?
- Create this POJO every time we want to call the method which needs it.
- Make it a singleton bean, create it once and then autowire it?
答案1
得分: 2
Spring Boot提供了 @ConfigurationProperties 机制 来自动化这个过程。通常情况下,最好避免直接依赖于 MyServiceProperties,而是在 @Bean 方法中进行注入,但 MyServiceProperties 实例可作为上下文Bean使用。
英文:
Spring Boot provides the @ConfigurationProperties mechanism specifically to automate this for you. In general, it's best to avoid direct dependencies on MyServiceProperties and to do the injection in an @Bean method, but the MyServiceProperties instance is available as a context bean.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论