Use your class as a bean in Spring Boot

Depending on your needs, you can either leverage @ComponentScan to automatically detect your class and have an instance created, use it together with @Autowired and @Value to get dependencies or properties injected, or you can use a method annotated with @Bean to have more control over the construction of the bean being created

Spring project main class

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

public class DemoApplication {

	public static void main(String[] args) {, args);

Using @Component

package com.example.demo;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

public class HelloBean {

	public void sayHello() {
		System.out.println("Hello world, from spring bean");

Spring Boot will detect this class and create a bean instance from it. The @PostConstruct annotated method is invoked after construction and injection of all dependencies.


Hello world, from spring bean


You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *