Creating an Example of Bean and Component Injection in Spring Boot
Overview
In this lab, you will create a simple Spring Boot application demonstrating both Bean Injection and Component Injection.
You will use Spring Initializr to generate the project and follow the provided structure and naming conventions.
Project Setup
- Group: com.neueda
- Artifact: di-config-bean-demo
- Name: di-config-bean-demo
- Dependencies:
- Spring Web
- Spring Boot DevTools (optional, for easier testing)
Project Structure and File Locations
You will store your files in the following locations inside the src/main/java/com/neueda/di_config_bean_demo directory.
1. Service Interface
- Package: service
- File: GreetingService.java
- Description:
- Create an interface called GreetingService.
- Define a method
String greet();
Click here to view the example solution
public interface GreetingService {
String greet();
}
2. Bean Implementation
- Package: service
- File: MorningGreetingService.java
- Description:
- Create a class MorningGreetingService that implements GreetingService.
- Register this class as a @Bean in a configuration class (see below).
Click here to view the example solution
import org.springframework.stereotype.Component;
@Component
public class MorningGreetingService implements GreetingService {
@Override
public String greet() {
return "Good morning!";
}
}
3. Configuration Class
- Package: config
- File: ServiceConfig.java
- Description:
- Create a configuration class ServiceConfig.
- Define a @Bean method that returns a MorningGreetingService.
Click here to view the example solution
import org.springframework.context.annotation.Bean;
import com.neueda.di_config_bean_demo.service.GreetingService;
import com.neueda.di_config_bean_demo.service.MorningGreetingService;
public class ServiceConfig {
// This method returns a new instance of the MorningGreetingService
@Bean
public GreetingService morningGreetingService() {
return new MorningGreetingService();
}
}
4. Component Class
- Package: component
- File: GreeterComponent.java
- Description:
- Create a class GreeterComponent.
- Annotate it with @Component.
- Inject GreetingService using constructor injection.
- Call the greet() method inside a method named sayHello().
Click here to view the example solution
import org.springframework.stereotype.Component;
import com.neueda.di_config_bean_demo.service.GreetingService;
@Component
public class GreeterComponent {
private final GreetingService greetingService;
// Constructor injection of the GreetingService
public GreeterComponent(GreetingService greetingService) {
this.greetingService = greetingService;
}
// Method to use the greeting service
public String sayHello() {
return greetingService.greet();
}
}
5. Main Application Class
- Package: com.neueda.di_config_bean_demo
- File: DiConfigBeanDemoApplication.java
- Description:
- Modify the main class to run the application.
- Use ApplicationContext / CommandLineRunner to get the GreeterComponent bean.
- Call the sayHello() method when the application starts.
Click here to view the example solution
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.neueda.di_config_bean_demo.component.GreeterComponent;
@SpringBootApplication
public class DiConfigBeanDemoApplication {
private final Logger logger = LoggerFactory.getLogger(DiConfigBeanDemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(DiConfigBeanDemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(GreeterComponent greeterComponent) {
return args -> {
// Use the greeter component to print a greeting
logger.info(greeterComponent.sayHello());
};
}
}
Deliverables
By the end of the lab, you should have a working Spring Boot application that:
- Uses a manually configured Bean (MorningGreetingService)
- Injects the Bean into a Component (GreeterComponent)
- Outputs a greeting message to the console when the application starts.
Extension Task
Now try to implement more than one type of greeting class:
- MorningGreeting
- EveningGreeting
- NightGreeting
Steps:
-
Open application.properties:
- Look for this file inside the resources folder (src/main/java)
- If the file doesn't exist create it
-
Add the line
greeting.type=morning(or evening, night) -
Save the file
-
Remove the @Component annotation from all of the Service classes (inside service folder)
-
Add a @Configuration annotation to the ServiceConfig class
-
Create an instance variable called greetingType of type String
-
Add a Value annotation
@Value("${greeting.type:morning}")to the variable -
Rename the function in the ServiceConfig class from morningGreetingService to currentGreetingService
-
Inside this class use the switch statement to return the relevant service class (morning, evening, night) based on the value of the greetingType variable
-
Run the application and you should see your morning message logged.
-
Change the value of application.properties to evening / night and rerun the application
-
The message output should change
Solution
EveningGreetingService.java
Click here to view the example solution
public class EveningGreetingService implements GreetingService {
@Override
public String greet() {
return "Good evening!";
}
}
NightGreetingService.java
Click here to view the example solution
public class NightGreetingService implements GreetingService {
@Override
public String greet() {
return "Good night!";
}
}
application.properties
Click here to view the example solution
spring.application.name=di-config-bean-demo
greeting.type=night
Remove @Component annotation from Service Classes
Click here to view the example solution
EveningGreetingService.java
public class EveningGreetingService implements GreetingService {
@Override
public String greet() {
return "Good evening!";
}
}
MorningGreetingService.java
public class MorningGreetingService implements GreetingService {
@Override
public String greet() {
return "Good morning!";
}
}
NightGreetingService.java
public class NightGreetingService implements GreetingService {
@Override
public String greet() {
return "Good night!";
}
}
Add @Configuration annotation to the ServiceConfig class
Click here to view the example solution
// This class is a configuration class that defines beans for
// different greeting services
@Configuration
public class ServiceConfig {
// This property can be set in application.properties
// If not set, it defaults to "morning"
@Value("${greeting.type:morning}")
public String greetingType;
// This method returns a new instance of the MorningGreetingService
@Bean
public GreetingService currentGreetingService() {
switch (greetingType.toLowerCase()) {
case "evening":
return new EveningGreetingService();
case "night":
return new NightGreetingService();
case "morning":
default:
return new MorningGreetingService();
}
}
}