Spring Boot Annotations and managed objects

CDI Contexts and Dependency Injection provides the programmer with a mechanism that automatically manages class instances. The main advantages are:
  • No need to create classes using the new keyword ;
  • No need to pass a class instance to call its method in a different class.
For comparison

Code written in Java SE:

1
2
3
4
5
public class Hello {
    public String sayHallo() {
        return "Hello!";
    }
}

1
2
3
4
5
6
public class Sample {
    public static void main(String[] args) {
        Hello hello = new Hello();
        hello.sayHallo();
    }
}

The code written in Spring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootApplication
public class HelloApplication {
 
    @Autowired
    Hello hello;
 
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args); // uruchomienie kontekstu springa
    }
 
    @PostConstruct
    public void init() {
        System.out.println(hello.sayHallo());
    }
}
1
2
3
4
5
6
@Service
public class Hello {
    public String sayHallo() {
        return "Hello!";
    }
}
The result of both programs is identical. Beginners may find it difficult to use annotations. The assimilation of these principles translates into a fruitful profit - the code is much simpler, shorter, which determines the ease of its maintenance.
What deserves special attention is annotation in the Hello class which is @Service. Well, in order to use the dependency management mechanism, we should indicate Spring the class that we want to cover with such benefits. The above-mentioned annotation serves this purpose.
The @Component annotation is the most general annotation that can be used for this purpose. This is information only for the compiler that this class will manage by the Spring context.
There are also other - specialized annotations that perform the same functions but are recommended for use depending on the case. They are:
  • @Component - mentioned at the beginning the most general one
  • @ Repository - dedicated to classes that, in their opinion, are stored, aggregated data
  • @Service - dedicated to classes that provide services
  • @ Controller / @ RestController - dedicated for the presentation layer and / or for the application API
On classes that have one of the above annotations and have been run under the Spring context - name themselves as managed objects.
The next article will present cases when to use the bean management mechanism, and when to leave the unmanaged class.

Related blog:

Comments

Popular posts from this blog

How to convert Stream to Set using java

Java Concurrency Method basic example

How to Learn Java Effectively