Spring Standard Bean Injection vs. Autowiring Spring Standard Bean Injection vs. Autowiring spring spring

Spring Standard Bean Injection vs. Autowiring


First of all you should add @Service or @Component to the SimpleUserService class.

  • 1 Yes, the ONE instance of UserPreferences is created at application intialization
  • 2 Default scope is singleton, You can change it with the @Scope annotation (@See Spring Reference: 3.11.4.4 Specifying bean scope)
  • 3 Component scan and XML configuration work in the same way (life cycle)

Maybe you should spend some time in understanding the Spring life cycle. You need to understand that Spring works a bit in this way (not 100% correct):

  • first it creates a pool of beans
  • then it injects the properties into the beans

But it does NOT work this way: taking a class, look what references it needs creating this references (recursive) and then creating the class.

If you understand this, then you will also understand, that the @Scope of a bean is defined at the bean declaration/class, but not at the references.


1) Is userPreference created on Application init?

In either case userPreferences is initialized when Spring Context is loaded. You can change this behavior by adding lazy-init="true" to the bean configuration.

2) What is the default scope for bean injected by autowire and how can we change it?

The scope of what is injected is all beans loaded into Spring. If you import an XML configuration from another project, it too would be included. I'm not sure if you can limit your scope.

3) How affects bean creation and bean injection?

Whether is autowired, or configured via XML, the behavior should be the same. I prefer explicitly defining dependencies over automatic annotations. Then again I also like strongly typed languages.


the configuration above means that userService and userPreferences created when application starts. Is it correct?

Yes

Is userPreference created on Application init?

Yes

What is the default scope for bean injected by autowire and how can we change it?

The default scope is always "singleton". This can be changed either using @Scope with @Bean or the scope XML attribute on <bean>.

How affects bean creation and bean injection?

This isn't a clear question. If you change the bean scope, you change when it gets created (start of application, on each request, on each session, etc). The wiring configuration remains the same, only the lifecycle changes.