1.Configuration
@Configuration
是 Spring 框架中的一个注解,用来标识一个类是一个配置类。这个配置类通常包含一个或多个 @Bean
注解的方法,这些方法会被 Spring 容器调用,以实例化、配置和初始化一个新的对象,这些对象将被管理为 Spring 容器中的 Bean。
使用 @Configuration
注解的类就相当于传统的 Spring XML 配置文件。
示例
我们来创建一个简单的示例,展示如何使用 @Configuration
注解。
1. 创建 Bean 类
首先,我们创建一个简单的 Bean 类,例如 ExampleService
:
javaCopy Code
package com.example;
public class ExampleService {
private String message;
public ExampleService(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
2. 创建配置类
接下来,我们创建一个配置类,并使用 @Configuration
注解。我们将通过 @Bean
注解定义一个 ExampleService
的实例:
package com.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public ExampleService exampleService() { return new ExampleService("Hello from ExampleService"); } }
在这个配置类中,exampleService
方法被 @Bean
注解标记,这意味着这个方法将返回一个被 Spring 容器管理的 Bean 实例。在这里,我们创建并返回了 ExampleService
的实例。
3. 启动 Spring 容器并获取 Bean
我们编写一个主类来启动 Spring 容器,并从容器中获取我们定义的 Bean:
package com.example; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MainApp { public static void main(String[] args) { // 使用 AnnotationConfigApplicationContext 来加载配置类 ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // 获取 ExampleService Bean ExampleService service = context.getBean(ExampleService.class); // 输出消息 System.out.println(service.getMessage()); } }