0
0
Spring Bootframework~30 mins

@Configuration and @Bean in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @Configuration and @Bean in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that needs a custom service bean to provide greetings. You want to configure this bean using Spring's @Configuration and @Bean annotations.
🎯 Goal: Create a Spring Boot configuration class that defines a bean of type GreetingService. This bean will be used to provide greeting messages in the application.
📋 What You'll Learn
Create a class annotated with @Configuration
Define a method annotated with @Bean that returns a GreetingService instance
The GreetingService class should have a method getGreeting() returning a greeting string
Use the bean method to return a new GreetingService object
💡 Why This Matters
🌍 Real World
Spring Boot applications use @Configuration and @Bean to manage and configure components and services cleanly and flexibly.
💼 Career
Understanding how to define and use beans with @Configuration and @Bean is essential for backend Java developers working with Spring Boot.
Progress0 / 4 steps
1
Create the GreetingService class
Create a public class called GreetingService with a public method getGreeting() that returns the string "Hello, Spring!".
Spring Boot
Need a hint?

Define a simple class with a method that returns a fixed greeting string.

2
Create a configuration class with @Configuration
Create a public class called AppConfig and annotate it with @Configuration.
Spring Boot
Need a hint?

Use @Configuration annotation from Spring to mark the class as a configuration.

3
Define a @Bean method returning GreetingService
Inside the AppConfig class, create a public method called greetingService() annotated with @Bean that returns a new instance of GreetingService.
Spring Boot
Need a hint?

Use @Bean annotation on a method that returns a new GreetingService object.

4
Use the GreetingService bean in a component
Create a public class called GreetingPrinter with a private final GreetingService field. Add a constructor that accepts a GreetingService parameter and assigns it to the field. Add a public method printGreeting() that returns the result of greetingService.getGreeting().
Spring Boot
Need a hint?

Create a class that uses the GreetingService bean by constructor injection and calls its method.