Configuration注解

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()); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值