gpt4 book ai didi

java - 如何在bean方法中注入(inject)字段?

转载 作者:行者123 更新时间:2023-12-02 08:40:33 26 4
gpt4 key购买 nike

Sonar-linter 认为正确的注入(inject)方式是:

@Bean
public Example example(DataSource datasource) {
return new Example(datasource)
}

但如果只有一种方法使用该字段。我很好奇,为什么只有一种方法?也许@Autowired 更好?

引用声纳规则:

When @Autowired is used, dependencies need to be resolved when the class is instantiated, which may cause early initialization of beans or lead the context to look in places it shouldn't to find the bean. To avoid this tricky issue and optimize the way the context loads, dependencies should be requested as late as possible. That means using parameter injection instead of field injection for dependencies that are only used in a single @Bean method

最佳答案

正如您的引用所说,@Autowired 需要在类初始化时解决依赖关系。参数注入(inject)仅在需要时实例化 bean。这会提高代码的有效性。Single Method 的原因是由 Bean 的生命周期引起的。默认情况下,Bean 是单例,这意味着它们像静态对象一样被共享。因此,如果多个对象将使用该 bean,则使用 Autowiring 注入(inject)它们会更有效,因为使用它的可能性要高得多,因此您在启动时提供 Shared 实例

关于java - 如何在bean方法中注入(inject)字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61414744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com