Skip to main content

Spring in depth 1

·316 words·2 mins
Table of Contents
Spring - This article is part of a series.
Part : This Article

Spring in Depth 1
#

Auto wiring
#

Auto wiring looks for a dependency that implements the interface that is auto-wired. Let’s just look at a sample case below

@Component
public class ClientApp{
    @Autowired
    Service reqService;
}
@Component
public class SplService implements Service{
}
@Component
public class NormService implements Service{
}

Now, we have looked already what happens if there are 2 dependencies. It will throw an error as its not able to define a dependency as nothing is defined as primary.

So, we can mark one of the implementation with @Primary.

@Component
@Primary
public class NormService implements Service{
}

Another way to do this is auto-wiring by name.

@Component
public class ClientApp{
    @Autowired
    Service normService;
}

Now, it looks at NormService as the service is named with a implementing class name. But what if both types of auto wiring is present. Then @Primary will take precedence over auto wiring by name.

Another way is to auto wire by @Qualifier.

@Component
public class ClientApp{
    @Autowired
    @Qualifier("spl")
    Service reqService;
}
@Component
@Qualifier("Spl")
public class SplService implements Service{
}

@Qualifier takes precedence over @Primary and auto wiring by name

Bean Scope
#

Spring creates all the beans and maintains them. By default, the scope of the bean is singleton.

  • singleton - One instance per Spring Context
  • prototype - One instance per request
  • request - One bean per HTTP request
  • session - One bean per HTTP session

To configure a bean as prototype, we can use the following annotation.

@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

Singleton vs Prototype Scope
#

Singleton Prototype
Default Scope, no explicit annotation required Need to set the scope explicitly like shown above
Only one instance per Spring Container One instance per request
Same object returned each time injected New object created each time injected
Used for stateless scenarios Used for stateful

We will look at further concepts like Life Cycle of a bean, Application context, etc in future posts

Spring - This article is part of a series.
Part : This Article