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; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
Using @Component
package com.example.demo; import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; @Component public class HelloBean { @PostConstruct 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.
Output
Hello world, from spring bean