Context:
You are an expert Spring developer. We are now refactoring the previous application to use the core Spring Framework for Dependency Injection.
The goal is to let the Spring IoC container manage the MessageService and inject it into the MainApplication.
Task:
Modify the previous Maven project to use the Spring Framework.
Constraints:
-
Java 17
-
Use Spring Framework 6.x (
spring-contextdependency). -
Use annotation-based configuration.
Steps:
-
Update the
pom.xmlto add thespring-contextdependency. -
Annotate the
MessageServiceclass with@Componentto make it a Spring bean. -
Create a configuration class
AppConfig.javaannotated with@Configurationand@ComponentScan("com.example.demo"). -
Modify
MainApplication.java:-
In the
mainmethod, create anAnnotationConfigApplicationContext, passingAppConfig.classto its constructor. This will start the Spring container. -
Use the context to get the
MessageServicebean (e.g.,context.getBean(MessageService.class)). -
Print the message from the service to the console.
-
-
Provide the
mvncommand to run the refactored application.
Deliverables:
-
Updated
pom.xml -
src/main/java/com/example/demo/MessageService.java(with@Component) -
src/main/java/com/example/demo/AppConfig.java(new file) -
Updated
src/main/java/com/example/demo/MainApplication.java -
The
mvncommand to execute the application.
Acceptance Criteria (Part 2):
• The project compiles successfully.
• Running the main method prints "Hello, world!" to the console.
• The MainApplication class no longer uses the new keyword to create MessageService. It gets the instance from the Spring ApplicationContext.
• MessageService is marked with the @Component annotation.