Skip to main content

Spring Framework Basics

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

Basics of Spring Framework
#

We will look at the basics of Spring Framework.

To start with we will create a sample project using Spring Initializer. Click on generate to download the project as a archive, unzip it and import it as a maven project into Eclipse. We can run the java file with main method to ensure our project is working.

We will take the example we saw in the last post as example to walk through the concepts. Let’s assume we have got to a loosely coupled code below,

public class ClientApp{
    Service reqService;
    public ClientApp(Service reqService){
        this.reqService = reqService;
    }
}
public class NormService implements Service{
public class SplService implements Service{

Usage of above code as follows for loose coupling

SplService splService = new SplService(); //Can be changed to NormService if required 
ClientApp app = new ClientApp(splService);

Now, we would like to achieve same in Spring Framework. There would be no need for us to call the code to create an instance of service. We can get a managed bean from application context. To achieve that we will use 2 annotations.

@Component - To make the class a managed bean @Autowired - To automatically resolve and inject the dependency

@Component
public class ClientApp{
    @Autowired
    Service reqService;
    public ClientApp(Service reqService){
        this.reqService = reqService;
    }
}
@Component
public class NormService implements Service{

In the above example Spring will automatically auto-wire the NormService with reqService variable via constructor. Log entry will be like below

2021-12-16 19:54:49.552 DEBUG 3284 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Autowiring by type from bean name 'clientApp' via constructor to bean named 'normService'

The above bean can be manually accessed by following code for testing,

ApplicationContext applicationContext = 
		SpringApplication.run(SampleApp.class, args);
ClientApp clientApp = applicationContext.getBean(ClientApp.class);

If we have 2 Components that match the same @Autowired component, it will fail. At that time, we can either,

  • Remove @Component from one of the Class
  • Add @Primary to one of them

We have another way of injecting the dependency other than Constructor injection we saw above, that is Setter Injection. We achieve that by following means,

@Component
public class ClientApp{
    @Autowired
    Service reqService;
    public setReqService(Service reqService){
        this.reqService = reqService;
    }
}

We can see the debug log as follows, the ‘by constructor’ part is gone. We will get same result if there are no setters as well.

Autowiring by type from bean name 'clientApp' to bean named 'normService'
Spring - This article is part of a series.
Part : This Article