You are on page 1of 60

@Component : It indicates that annotated class is spring bean /Component.

It tells spring container to


automatically create a Spring bean .

Spring IOC container will take care of creating beans.We don't have to create object

of the class using new keyword.

Create controller package->PizzaController.java

package com.codingmaster.springannotations.controller;

import org.springframework.stereotype.Component;

@Component

public class PizzaController {

public String getPizza(){

return "Hot Pizza";

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication

public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class, args);

PizzaController pizzaController=context.getBean(PizzaController.class);

System.out.println(pizzaController.getPizza());

Output:

Hot Pizza

We can retreive spring bean by using name also:

first letter should be lower case

PizzaControlle.java

package com.codingmaster.springannotations.controller;
import org.springframework.stereotype.Component;

@Component("demopizza")

public class PizzaController {

public String getPizza(){

return "Hot Pizza";

Spring main application

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class, args);


PizzaController pizzaController= (PizzaController) context.getBean("demopizza");

System.out.println(pizzaController.getPizza());

3)We can also access using Classname:

package com.codingmaster.springannotations.controller;

import org.springframework.stereotype.Component;

@Component

public class PizzaController {

public String getPizza(){

return "Hot Pizza";

}
package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class, args);

PizzaController pizzaController= (PizzaController) context.getBean("pizzaController");

System.out.println(pizzaController.getPizza());

}
Conclusion:Here we are using @Component Annotation to create spring bean automatically in Spring
container. We don't

have to create object using new keyword.Spring IOC container takes care of managing object for us.

2)

@Autowired ->

it is used to inject the beans automatically

used in->

1.constructor ,setter and field injection.

create service package->

and create VegPizza.java class inside package

->write below code and inject @Autowired in PizzaController

VegPizza.java

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component
public class VegPizza {

public String getPizza(){

return "veg Pizza";

Step-2

Inject->veg pizza in Pizza Controller and get the data using annotation

1.create instance variable of VegPizza class

1.Inject using Constructor

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component

public class VegPizza {

public String getPizza(){

return "veg Pizza";

}
PizzaController.java

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.VegPizza;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class PizzaController {

private VegPizza vegPizza;

@Autowired

public PizzaController(VegPizza vegPizza){

this.vegPizza=vegPizza;

public String getPizza(){

return vegPizza.getPizza();

RUn Spring bootmain application

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;
import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class, args);

PizzaController pizzaController= (PizzaController) context.getBean("pizzaController");

System.out.println(pizzaController.getPizza());

Output:

veg Pizza

2.Inject using Setter Method :

package com.codingmaster.springannotations.controller;
import com.codingmaster.springannotations.service.VegPizza;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component

public class VegPizza {

public String getPizza(){

return "veg Pizza";

@Component

public class PizzaController {

private VegPizza vegPizza;

// Using Constructor
// @Autowired

// public PizzaController(VegPizza vegPizza){

// this.vegPizza=vegPizza;

// }

//inject using setter method

@Autowired

public void setVegPizza(VegPizza vegPizza) {

this.vegPizza = vegPizza;

public String getPizza(){

return vegPizza.getPizza();

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class, args);

PizzaController pizzaController= (PizzaController) context.getBean("pizzaController");

System.out.println(pizzaController.getPizza());

3.Inject dependecny usinf Field

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.VegPizza;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

Step-1

@Component

public class PizzaController {


//Inject using field

@Autowired

private VegPizza vegPizza;

// Using Constructor

@Autowired

public PizzaController(VegPizza vegPizza){

this.vegPizza=vegPizza;

//inject using setter method

@Autowired

public void setVegPizza(VegPizza vegPizza) {

this.vegPizza = vegPizza;

public String getPizza(){

return vegPizza.getPizza();

Step-2
package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component

public class VegPizza {

public String getPizza(){

return "veg Pizza";

Step-3

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringannotationsApplication {


public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class, args);

PizzaController pizzaController= (PizzaController) context.getBean("pizzaController");

System.out.println(pizzaController.getPizza());

Run Spring boot main->

Output->Veg pizza

it will come from getPizza in service class.

3)

@Qualifier Annotation->

it is used in conjuction with Autowired to avoid confusion when

we have 2 or more beans configured for same type

1.In Service Package->Create interface with name

Pizza.java(I)

VegPizza class->Implement above Pizza.java interface

NonVegPizza class->Implement Pizz.java interface and override method


with implementation

Pizza.java(I)

package com.codingmaster.springannotations.service;

public interface Pizza {

String getPizza();

2)

VegPizza(C)

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component

public class VegPizza implements Pizza {

@Override

public String getPizza() {

return "Veg Pizza";

}
}

3)

NonVegPizza(C)

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component

public class NonVegPizza implements Pizza{

@Override

public String getPizza() {

return "Non-Veg pizza";

Inject interface to acheive loose coupling -

It will give loose coupling

controller-PizzaController
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;

import com.codingmaster.springannotations.service.VegPizza;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

@Component

public class PizzaController {

private Pizza pizza;

// Using Constructor

@Autowired

public PizzaController(Pizza pizza){

this.pizza=pizza;

public String getPizza(){

return pizza.getPizza();

It will give error:


Parameter 0 of constructor in com.codingmaster.springannotations.controller.PizzaController required a
single bean, but 2 were found:

- nonVegPizza: defined in file [D:\springannotations\target\classes\com\codingmaster\


springannotations\service\NonVegPizza.class]

- vegPizza: defined in file [D:\springannotations\target\classes\com\codingmaster\


springannotations\service\VegPizza.class]

So to avoid this error,use @Qualifier annotation in constructor

with @Qualifier("classname in lowercase")->

this is name for spring bean

Replace above code with below code :

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;

import com.codingmaster.springannotations.service.VegPizza;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Component;

@Component

public class PizzaController {


private Pizza pizza;

// Using Constructor

@Autowired

public PizzaController(@Qualifier("nonVegPizza") Pizza pizza){

this.pizza=pizza;

public String getPizza(){

return pizza.getPizza();

RUn Springboot app

Output:Non-Veg pizza

or

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;

import com.codingmaster.springannotations.service.VegPizza;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Component;
@Component

public class PizzaController {

private Pizza pizza;

// Using Constructor

@Autowired

public PizzaController(@Qualifier("vegPizza") Pizza pizza){

this.pizza=pizza;

public String getPizza(){

return pizza.getPizza();

RUn spirng boot

Veg Pizza

Conclusion:Spring IOC get confused which Pizza interface

implement it should provide so the reason ,we use @Qualifier

annotation
Final COde:

Pizza Interface

package com.codingmaster.springannotations.service;

public interface Pizza {


String getPizza();
}

VegPizza class

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component
public class VegPizza implements Pizza {

@Override
public String getPizza() {
return "Veg Pizza";
}
}

NonVegPizza class:

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Component;

@Component
public class NonVegPizza implements Pizza{
@Override
public String getPizza() {
return "Non-Veg pizza";
}
}

4)
Controllerpackage->PizzaController class

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class PizzaController {

private Pizza pizza;


// Using Constructor
@Autowired
public PizzaController(@Qualifier("vegPizza") Pizza pizza){
this.pizza=pizza;
}
public String getPizza(){
return pizza.getPizza();
}
}

Spring Boot main app:

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
System.out.println(pizzaController.getPizza());

}
4)

4.@Primary Annotation:

We use @Primary annotation to give higher preference to bean when there are multiple beans of

the same type

It is an alternative to @Qualifier annotation

In vegpizza or nonvegpizza class, add @primary annotation ->Add in one of them not for both.

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class PizzaController {

private Pizza pizza;


// Using Constructor
@Autowired
public PizzaController(Pizza pizza){
this.pizza=pizza;
}
public String getPizza(){
return pizza.getPizza();
}
}
package com.codingmaster.springannotations.service;

public interface Pizza {


String getPizza();
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@Primary
public class NonVegPizza implements Pizza{
@Override
public String getPizza() {
return "Non-Veg pizza";
}
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
//@Primary
public class VegPizza implements Pizza {

@Override
public String getPizza() {
return "Veg Pizza";
}
}

Run main :

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {
public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
System.out.println(pizzaController.getPizza());

Output

. ____ _ __ _ _

/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

\\/ ___)| |_)| | | | | || (_| | ) ) ) )

' |____| .__|_| |_|_| |_\__, | / / / /

=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v3.2.3)

2024-03-16T13:41:55.682+05:30 INFO 14288 --- [springannotations] [ main]


c.c.s.SpringannotationsApplication : Starting SpringannotationsApplication using Java 17.0.7 with PID
14288 (D:\springannotations\target\classes started by Digital Suppliers in D:\springannotations)

2024-03-16T13:41:55.684+05:30 INFO 14288 --- [springannotations] [ main]


c.c.s.SpringannotationsApplication : No active profile set, falling back to 1 default profile: "default"

2024-03-16T13:41:56.206+05:30 INFO 14288 --- [springannotations] [ main]


c.c.s.SpringannotationsApplication : Started SpringannotationsApplication in 0.842 seconds (process
running for 1.099)

Non-Veg pizza

Process finished with exit code 0


5.

@Bean Annotation->

it indicates that method producs a bean to be managed by spring container.

The @Bean is usually declared in COnfiguration class to create Spring Bean

Definitions.

1.Create a package Config ->

AppConfig->

Annotate class @Configuration->Now we can define spring bean

In Annotation based, we didn't create an object using new keyword

but in java based configuration->We are using new keyword to create

object using new keyword and telling Spring Container to manage the object

We need to rerieve object from Spring IOC container->

So we will go to main method->using context & getBean method()

Code:

Config- package->Appconfig.java

package com.codingmaster.springannotations.config;

import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {

@Bean
public Pizza vegPizza(){
return new VegPizza();
}
}

Remove annotation based configuration and run java based configuration:

TO remove annotation based configuration->Remove @Component annotation from vegpizza class

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

public class VegPizza implements Pizza {

@Override
public String getPizza() {
return "Veg Pizza";
}
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

//@Component
//@Primary
public class NonVegPizza implements Pizza{
@Override
public String getPizza() {
return "Non-Veg pizza";
}
}

package com.codingmaster.springannotations.service;

public interface Pizza {


String getPizza();
}
package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
// PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
// System.out.println(pizzaController.getPizza());

VegPizza vegPizza=context.getBean(VegPizza.class);
System.out.println(vegPizza.getPizza());
NonVegPizza nonvegPizza=context.getBean(NonVegPizza.class);
System.out.println(nonvegPizza.getPizza());

Code:2

This will execute both

Service package:

package com.codingmaster.springannotations.service;

public interface Pizza {


String getPizza();
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

public class VegPizza implements Pizza {


@Override
public String getPizza() {
return "Veg Pizza";
}
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

//@Component
//@Primary
public class NonVegPizza implements Pizza{
@Override
public String getPizza() {
return "Non-Veg pizza";
}
}

package com.codingmaster.springannotations.config;

import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class AppConfig {

@Bean
public Pizza vegPizza(){
return new VegPizza();
}
@Bean
@Primary
public Pizza nonvegPizza(){
return new NonVegPizza();
}
}

package com.codingmaster.springannotations;
import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
// PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
// System.out.println(pizzaController.getPizza());

VegPizza vegPizza=context.getBean(VegPizza.class);
System.out.println(vegPizza.getPizza());
NonVegPizza nonvegPizza=context.getBean(NonVegPizza.class);
System.out.println(nonvegPizza.getPizza());

Output:

Veg Pizza

Non-Veg pizza

We can even access with bean name as in below code:

package com.codingmaster.springannotations.config;

import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class AppConfig {

@Bean(name = "vegpizzabean")
public Pizza vegPizza(){
return new VegPizza();
}
@Bean(name = "nonvegpizzabean")
@Primary
public Pizza nonvegPizza(){
return new NonVegPizza();
}
}

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
// PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
// System.out.println(pizzaController.getPizza());

// VegPizza vegPizza=context.getBean(VegPizza.class);
VegPizza vegPizza= (VegPizza) context.getBean("vegpizzabean");//access
using bean name
System.out.println(vegPizza.getPizza());
// NonVegPizza nonvegPizza=context.getBean(NonVegPizza.class);
NonVegPizza nonvegPizza= (NonVegPizza)
context.getBean("nonvegpizzabean");
System.out.println(nonvegPizza.getPizza());

}
Bydefault ->we can access by using method name without wiring any name attribute in @Bean
annotation in spring

Conclusing->

Annotation based configuration(@Component ) vs Java Based configuration(@Bean,@Configuration


annotation)

So Remove @Autowired, @Component if don’t want annotation based configuration

Inject using PizzaController:

Config->AppConfig

package com.codingmaster.springannotations.config;

import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class AppConfig {

@Bean(name = "vegpizzabean")
public Pizza vegPizza(){
return new VegPizza();
}
@Bean(name = "nonvegpizzabean")
@Primary
public Pizza nonvegPizza(){
return new NonVegPizza();
}

@Bean
public PizzaController pizzaController(){
return new PizzaController(vegPizza());//call object of vegPizza class
}
}

controller-PizzaController:
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

public class PizzaController {

private Pizza pizza;


// Using Constructor
public PizzaController(Pizza pizza){
this.pizza=pizza;
}
public String getPizza(){
return pizza.getPizza();
}
}

service:

package com.codingmaster.springannotations.service;

public interface Pizza {


String getPizza();
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

public class NonVegPizza implements Pizza{


@Override
public String getPizza() {
return "Non-Veg pizza";
}
}

package com.codingmaster.springannotations.service;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
public class VegPizza implements Pizza {

@Override
public String getPizza() {
return "Veg Pizza";
}
}

Spring main :

package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
System.out.println(pizzaController.getPizza());

// VegPizza vegPizza=context.getBean(VegPizza.class);
// VegPizza vegPizza= (VegPizza) context.getBean("vegpizzabean");//access
using bean name
// System.out.println(vegPizza.getPizza());
// NonVegPizza nonvegPizza=context.getBean(NonVegPizza.class);
// NonVegPizza nonvegPizza= (NonVegPizza)
context.getBean("nonvegpizzabean");
// System.out.println(nonvegPizza.getPizza());

or Change method to non veg and run same:

package com.codingmaster.springannotations.config;
import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class AppConfig {

@Bean(name = "vegpizzabean")
public Pizza vegPizza(){
return new VegPizza();
}
@Bean(name = "nonvegpizzabean")
@Primary
public Pizza nonvegPizza(){

return new NonVegPizza();


}

@Bean
public PizzaController pizzaController(){

return new PizzaController(nonvegPizza());//call object of vegPizza


class
}
}

1.By Default ,the bean name is same as method name .

We can specify bean name using

@Bean(name="beanname")

2.@Bean annotation provides initMethod and destroyMethod

attributes to perform certain actions after bean initialization or

before bean destruction by a container

package com.codingmaster.springannotations.config;

import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class AppConfig {

@Bean(name = "vegpizzabean")
public Pizza vegPizza(){
return new VegPizza();
}
@Bean(name = "nonvegpizzabean")
@Primary
public Pizza nonvegPizza(){

return new NonVegPizza();


}

@Bean(initMethod = "init", destroyMethod = "destroy")


public PizzaController pizzaController(){

return new PizzaController(nonvegPizza());//call object of vegPizza


class
}
}

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.service.Pizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

public class PizzaController {

private Pizza pizza;


// Using Constructor
public PizzaController(Pizza pizza){
this.pizza=pizza;
}
public String getPizza(){
return pizza.getPizza();
}

public void init(){


System.out.println("Initalization");
}
public void destroy(){
System.out.println("Destruction");
}
}

Impact of not using @Component annotation

If you choose not to use the @Component annotation, Spring won't


automatically recognize and manage your class as a component. Here's what
happens if you don't use @Component:

1. No Automatic Bean Registration: Spring won't automatically register the


class as a bean. This means you won't be able to inject instances of this class
into other Spring-managed components using annotations like @Autowired.
2. Manual Bean Registration: You would need to manually register the class as
a bean in your Spring configuration. This can be done using XML
configuration or Java configuration classes like @Configuration classes. For
each class that you want Spring to manage, you'd need to define a
corresponding bean definition.
3. No Component Scanning: Spring component scanning won't detect the class
automatically. Component scanning is a feature of Spring that automatically
detects classes annotated with @Component, @Service, @Repository, or other
stereotype annotations. Without @Component, you would need to explicitly
specify the classes to be managed by Spring.
4. Dependency Injection Requires Explicit Configuration: If you want to inject
instances of your class into other components using dependency injection,
you would need to configure this explicitly in your Spring configuration.
5. Lifecycle Management: Spring won't handle the lifecycle of your class
automatically. You would need to manage its initialization, destruction, and
other lifecycle aspects manually.

In summary, while not using @Component gives you more control over how
your classes are managed by Spring, it also requires more manual
configuration and can be less convenient, especially for smaller or simpler
applications. @Component provides a convenient way to let Spring handle the
management of your classes, reducing boilerplate code and making your
application more maintainable.

1.@Controller,@Repository,@Service

These annotations are used to categorize Spring-managed components based on their roles
in
the application. @Controller is used to mark classes as controllers for handling web
requests,
@Service is used for business logic components, and @Repository is used for data access
components.

Project Structure-main

MyController.java

package com.codingmaster.springannotations.controller;

import org.springframework.stereotype.Controller;

@Controller
public class MyController {
public String hello(){
return "hello controller.";
}
}
MyRepository.java

package com.codingmaster.springannotations.repository;

import org.springframework.stereotype.Repository;

@Repository
public class MyRepository {
public String hello(){
return "hello repository";
}
}

MyService.java

package com.codingmaster.springannotations.service;

import org.springframework.stereotype.Service;

@Service
public class MyService {
public String hello(){
return "hello service";
}
}

@Lazy Annotation:
@Lazy Annotation can be used

@Configuration

@Component

@Bean Annotation

Eager initialization is recommended

Implementation:
package com.codingmaster.springannotations.lazy;

import org.springframework.stereotype.Component;

@Component
public class EagerLoader {
public EagerLoader() {
System.out.println("EagerLoader....");
}
}

package com.codingmaster.springannotations.lazy;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy
public class LazyLoader {
public LazyLoader() {
System.out.println("LazyLoader....");

}
}
package com.codingmaster.springannotations;

import com.codingmaster.springannotations.controller.MyController;
import com.codingmaster.springannotations.controller.PizzaController;
import com.codingmaster.springannotations.lazy.LazyLoader;
import com.codingmaster.springannotations.repository.MyRepository;
import com.codingmaster.springannotations.service.MyService;
import com.codingmaster.springannotations.service.NonVegPizza;
import com.codingmaster.springannotations.service.VegPizza;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringannotationsApplication {

public static void main(String[] args) {

var context=SpringApplication.run(SpringannotationsApplication.class,
args);
// PizzaController pizzaController= (PizzaController)
context.getBean("pizzaController");
// System.out.println(pizzaController.getPizza());
MyController myController = context.getBean(MyController.class);
System.out.println(myController.hello());
MyService myService = context.getBean(MyService.class);
System.out.println(myService.hello());
MyRepository myRepository = context.getBean(MyRepository.class);
System.out.println(myRepository.hello());

//Lazy Loader call


LazyLoader lazyLoader = context.getBean(LazyLoader.class);

// VegPizza vegPizza=context.getBean(VegPizza.class);
// VegPizza vegPizza= (VegPizza) context.getBean("vegpizzabean");//access
using bean name
// System.out.println(vegPizza.getPizza());
// NonVegPizza nonvegPizza=context.getBean(NonVegPizza.class);
// NonVegPizza nonvegPizza= (NonVegPizza)
context.getBean("nonvegpizzabean");
// System.out.println(nonvegPizza.getPizza());

}
@Controller Annotation:

Add Spring-boot-starter-Web depdency to build rest apis

@Controller and @ResponseBody and @RequestMapping annotation:


Create above folder structure for

Package-bean->Book class with below code:

package com.codingmaster.springannotations.bean;

public class Book {


private int id;
private String title;
private String description;

public Book(int id, String title, String description) {


this.id = id;
this.title = title;
this.description = description;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getTitle() {


return title;
}
public void setTitle(String title) {
this.title = title;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


this.description = description;
}

@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", description='" + description + '\'' +
'}';
}
}

2.Add Rest controller logic ->controller-BookController.java

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class BookController {

@RequestMapping("/hello-world")
@ResponseBody
public String hello(){
return "Hello WOrld";
}

@RequestMapping("/book")
@ResponseBody
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}
Whenever we annotate class @Controller, it become Spring MVC controller automatically Scan that
class and create bean for that class.

@Controller->is a specialization of Component class.

Inside controller, we create handle method and map them to send and receive request-
>@RequestBody in form of json format and write json into and return http response back to client.

@RequestMapping->to map incoming http request to method-

@RestController->Combination of @Controller and


@ResponseBody->in Spring 4.0
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@RequestMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}

Whenever ,you want to develop Restful webservices using Spring MVC ,then use

@RestController Annotation.

But if we want to develop Spring MVC Web application->then

Use @Controller annotation->that return view

@RequestMapping Annotation:
How to use @RequestMapping annotation at class level?

@RequestMapping(“/api”) in class-

So they will use base annotation and then map it

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@RequestMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}

@RequestMapping annotation with multiple uri:

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@RequestMapping(value={"/book","/corejava","/java"})
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}

http://localhost:8080/api/book

http://localhost:8080/api/corejava

http://localhost:8080/api/java

Output:

// 20240316202559

// http://localhost:8080/api/java
{

"id": 1,

"title": "Core Java",

"description": "James Gosling"

@Request Mapping with HTTP methods:

Bydefault-Get

methodAttribute to be used

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@RequestMapping(value={"/book","/corejava","/java"},
method= RequestMethod.GET
)
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}
@RequestMapping with Produces and consumes:

package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@RequestMapping(value={"/book","/corejava","/java"},
method= RequestMethod.GET,
produces =
{MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE},
consumes =
{MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE}
)
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}

@GetMapping Annotation:
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@GetMapping(value={"/book","/corejava","/java"})
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}
For one end point:
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@GetMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}
}

shortcut to @Requestmapping and http get method

2.@PostMapping annotation:
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@GetMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}

@PostMapping(value="/books/create",
consumes = MediaType.APPLICATION_JSON_VALUE)
public Book createBook(@RequestBody Book book){
System.out.println(book.getId());
System.out.println(book.getTitle());
System.out.println(book.getDescription());
return book;
}
}

adding http status-201->created


package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@GetMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}

@PostMapping(value="/books/create",
consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(value= HttpStatus.CREATED)
public Book createBook(@RequestBody Book book){
System.out.println(book.getId());
System.out.println(book.getTitle());
System.out.println(book.getDescription());
return book;
}
}
Http status using Response Entity class :
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {

@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@GetMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}

// @PostMapping(value="/books/create",
// consumes = MediaType.APPLICATION_JSON_VALUE)
// @ResponseStatus(value= HttpStatus.CREATED)
// public Book createBook(@RequestBody Book book){
// System.out.println(book.getId());
// System.out.println(book.getTitle());
// System.out.println(book.getDescription());
// return book;
// }

@PostMapping(value="/books/create",
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> createBook(@RequestBody Book book){
System.out.println(book.getId());
System.out.println(book.getTitle());
System.out.println(book.getDescription());
return new ResponseEntity<>(book,HttpStatus.CREATED);
}
}
@PutMapping annotation:

Use @pathannotation->to bind the value of url path


variable to method argument
@Requestbody->to retrieve json from request and
convert json into java book object
package com.codingmaster.springannotations.controller;

import com.codingmaster.springannotations.bean.Book;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

//@RestController->is an combination to @Controller and @ResponseBody


//@Controller
//@ResponseBody
@RestController
@RequestMapping("/api")
public class BookController {
@RequestMapping("/hello-world")
public String hello(){
return "Hello WOrld";
}

@GetMapping("/book")
public Book getBook(){
Book book=new Book(1,"Core Java","James Gosling");
return book;
}

// @PostMapping(value="/books/create",
// consumes = MediaType.APPLICATION_JSON_VALUE)
// @ResponseStatus(value= HttpStatus.CREATED)
// public Book createBook(@RequestBody Book book){
// System.out.println(book.getId());
// System.out.println(book.getTitle());
// System.out.println(book.getDescription());
// return book;
// }

// {
// "id":101,
// "title":"Python",
// "description":"Guido van rossum"
// }
// http://localhost:8080/api/books/create
@PostMapping(value="/books/create",
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Book> createBook(@RequestBody Book book){
System.out.println(book.getId());
System.out.println(book.getTitle());
System.out.println(book.getDescription());
return new ResponseEntity<>(book,HttpStatus.CREATED);
}

//update
// Use @pathannotation->to bind the value of url path variable to method
argument
// @Requestbody->to retrieve json from request and convert json into java
book object

@PutMapping(value="/books/update/{id}")
public ResponseEntity<Book> updateBook(@PathVariable int id, @RequestBody
Book updatedBook){
System.out.println(id);
System.out.println(updatedBook.getTitle());
System.out.println(updatedBook.getDescription());
updatedBook.setId(id);
return ResponseEntity.ok(updatedBook);
}

You might also like