kaylil_01
kaylil_01

Reputation: 133

How to inject fields in bean-methods?

Sonar-linter think that right way to inject is:

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

but if only one method's using this field. I'm curious, why exactly one method? And maybe better do @Autowired?

Quote from Sonar's rule:

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

Upvotes: 0

Views: 441

Answers (1)

FishingIsLife
FishingIsLife

Reputation: 2372

As your Quote says, @Autowired needs the dependency to be resolved when the class is Initialzed. Parameter Injection instantiates the bean only when it‘s needed. This increases the effectivity of your Code. The reason for the Single Method is caused by lifecycle of a Bean. By default Beans are singletons which means they are Shared like static Objects. So if multiple Objects will use the bean it is more effective to inject them with autowired because the possibility That it will be used is much higher and so you provide the Shared instance at Startup

Upvotes: 2

Related Questions