IOC | Dependency Injection | Beans | Scopes in Spring

Hasan Kadir Demircan
5 min readFeb 22, 2023

The principle of Inversion of Control IOC means rather than a class instantiate it’s dependency we give this control to a third party or a container to do so and it does this by dependency injection.

In other words;
IOC is a technique that takes the creation and management of dependencies from the code/developer.

It gets the information about the objects from a configuration file(XML) or Java Code or Java Annotations and Java POJO class.

It is one of the most important features of Spring Framework. In general, Spring is based on the Dependency Injection technique.

Dependency Injection

Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation.
For example, when we use 1 class which needs another/other class to calculate/process its own task. We need dependency injection approach to inject the other class.

Traditional Way

public class Holder {
private Handle myHandle = new Handle();
public void handleIt() {
handle.handleIt();
}
}

IoC

public class Holder {
private Handle myHandle;

public Holder(Handle injectedHandle) {
myHandle = injectedHandle;
}

public void handleIt() {
handle.handleIt();
}
}

Advantage of IoC:
- Loose coupling development (Flexibility)
- It helps to write our code with SOLID principles
- Helps in Unit testing.
- Extending the application becomes easier. (added new class, update the methods etc.. )

I would like to talk a bit about @Autowired annotation

Spring beans can be declared either by Java configuration or XML configuration. By declaring beans, you provide metadata to the Spring Container to return the required dependency object at runtime. This is called Spring Bean Autowiring. In java based configuration, all the bean methods are defined in the class with @Configuration annotation. At runtime, Spring will provide bean definitions by reading those methods. Using @Autowired, the right dependency is assigned by the Spring Container.

In other words; Spring @Autowired annotation is used for automatic dependency injection. Spring framework is built on dependency injection and we inject the class dependencies through spring bean configuration file.

Constructor Injection with @Autowired

@Component
public class ConstructorInjectedStoreService {

private final EmployeeService employeeService;
private final ManagerService managerService;

@Autowired
public ConstructorInjectedStoreService(EmployeeService employeeService,
ManagerService managerService) {
this.employeeService = employeeService;
this.managerService = managerService;
}
}

Field Injection with @Autowired

@Component
public class FieldInjectedStoreService {

@Autowired
private EmployeeService employeeService;

@Autowired
private ManagerService managerService;
}

In contrast to the constructor injection, when a bean is created it may not have all its dependencies injected right away. Though, Spring will wire all dependencies to the target bean eventually

Setter Injection with @Autowired

@Component
public class SetterInjectedStoreService {

private EmployeeService employeeService;
private ManagerService managerService;

@Autowired
public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;
}

@Autowired
public void setManagerService(ManagerService managerService) {
this.managerService = managerService;
}
}

Here, we have the SetterInjectedStoreService bean whose setter methods are annotated with @Autowired. So during the creation of SetterInjectedStoreService bean, Spring will call these setter methods with related bean instances.

Optional Autowired -> Autowired(required=false)

So far, all of our dependencies were required. If Spring fails to find a suitable bean for the dependency, it will fail the application startup.

@Component
public class OptionalDependencyStoreService {

private final EmployeeService employeeService;
private final ManagerService managerService;

@Autowired(required = false)
private OrderService orderService;

@Autowired
public OptionalDependencyStoreService(EmployeeService employeeService,
ManagerService managerService) {
this.employeeService = employeeService;
this.managerService = managerService;
}
}

Here, we’ve annotated OrderService field with @Autowired. Note that we’re setting the required attribute to false. Hence, if Spring cannot find a suitable bean for OrderService, it will continue with the application startup.

Speaking of @Autowired, we should also mention the @Qualifier annotation.

The @Qualifier annotation in Spring is used to differentiate a bean among the same type of bean objects. If we have more than one bean of the same type and want to wire only one of them then use the @Qualifier annotation along with @Autowired to specify which exact bean will be wired.

Let’s see in an example;
Interface

public interface Car {

void startEngine();

}

Bmw class

@Component
public class Bmw implements Car {

@Override
public void startEngine() {

System.out.println("engineen has been started - Bmw");
}
}

Ford class

@Component
public class Ford implements Car {

@Override
public void startEngine() {

System.out.println("engineen has been started - Ford");
}
}

Qualifier Example

@Service
public class ServiceClass {

@Autowired
@Qualifier("Ford")
private Car car;

}

Beans

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

Spring Bean Configuration

Spring Framework provides three ways to configure beans to be used in the application.

  1. Annotation Based Configuration — By using @Service or @Component annotations. Scope details can be provided with @Scope annotation.
  2. XML Based Configuration — By creating Spring Configuration XML file to configure the beans. If you are using Spring MVC framework, the xml based configuration can be loaded automatically by writing some boiler plate code in web.xml file.
  3. Java Based Configuration — Starting from Spring 3.0, we can configure Spring beans using java programs. Some important annotations used for java based configuration are @Configuration @ComponentScan and @Bean

@Component : class-level annotation which by default denotes a bean with the same name as the class name with a lowercase first letter. It can be specified a different name using the value argument of the annotation

  1. @Repository : class-level annotation representing the DAO layer of an application; it enables an automatic persistence exception translation.
  2. @Service : class-level annotation representing where the business logic usually resides and can flavor the reuse of the code.
  3. @Controller : class-level annotation representing the controllers in Spring MVC (Model-View-Controller). @RestController for the REST “mode”.
  4. @Configuration : class-level annotation to say that it can contain bean definition methods annotated with @Bean

Bean Scopes;

1. Singleton : it means the container creates a single instance of that bean and when requested (by name or type) the same object will be returned
2. Prototype : a different instance is created every time it is requested from the container.
3. Request : creates a bean instance for a single HTTP request
4. Session : creates a bean instance for each HTTP session
5. Application : creates a bean instance for the lifecycle of a ServletContext
6. WebSocket : creates a bean instance for a particular WebSocket session.

Short additional information :
Stateless Beans: beans that are singleton and are initialized only once. The only state they have is a shared state. These beans are created while the ApplicationContext is being initialized. The SAME bean instance will be returned/injected during the lifetime of this ApplicationContext.

Stateful Beans: Beans that can carry state (instance variables). These are created EVERY time an object is required (like using the “new” operator in java).

Thanks;
https://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/html/beans.html

https://www.tutorialspoint.com/spring/spring_bean_definition.htm
https://www.interviewbit.com/spring-interview-questions/
https://www.baeldung.com/spring-bean-scopes#:~:text=The%20scope%20of%20a%20bean,prototype
https://www.digitalocean.com/community/tutorials/spring-ioc-bean-example-tutorial
https://stackoverflow.com/questions/4506241/stateful-beans-and-stateless-beans-in-spring-context

--

--