Home > AI > Backend > SpringBoot >

@Component

Example 1: convient for the context to find

MathComponent.java

@Component
public class MathComponent {

    public int add(int x, int y) {
        return x + y;
    }
}

DemoApplication.java

@SpringBootApplication
@RestController
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);


        try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
            context.scan("com.example.demo");
            context.refresh();

            MathComponent ms = context.getBean(MathComponent.class);

            int result = ms.add(1, 2);
            System.out.println("Addition of 1 and 2 = " + result);
        }
    }
}

Example 2: give the component a name

MathComponent.java

@Component("mc")
public class MathComponent {

    public int add(int x, int y) {
        return x + y;
    }
}

DemoApplication.java

@SpringBootApplication
@RestController
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);

        try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
            context.scan("com.example.demo");
            context.refresh();

//            MathComponent ms = context.getBean(MathComponent.class);
            MathComponent ms = (MathComponent) context.getBean("mc");


            int result = ms.add(1, 2);
            System.out.println("Addition of 1 and 2 = " + result);
        }
    }
}

Leave a Reply