@Configuration
注解
@Configuration
注解标记在类上,表明该类是一个配置类,这个类可以包含一个或多个@Bean
注解的方法,用于定义实例化Bean的逻辑。Spring容器在启动时会自动扫描这些配置类,并根据它们来生成和管理相应的Bean。
语法与注意事项:
@Configuration
标记的类通常放在项目的根包下,便于Spring扫描。- 配置类本身也是一个组件,它也会被Spring容器管理。
- 配置类中可以使用
@Bean
注解定义Bean,也可以使用@Import
引入其他配置类,或使用@ComponentScan
指定扫描的包。 - 在配置类中定义的Bean,默认是单例的。
@Bean
注解
@Bean
注解标记在方法上,用来声明一个Bean,方法的返回值就是要注入的Bean实例。@Bean
方法可以有参数,这些参数自动被Spring容器管理的Bean所填充。
语法与注意事项:
@Bean
方法所在的类,需要使用@Configuration
标记,确保Spring可以处理其中的Bean定义。- 可以通过
name
属性为Bean指定一个或多个名称,默认情况下,Bean的名称是方法的名称。 - Bean的作用域默认是单例(Singleton),也可以通过
@Scope
注解来指定其他作用域,如Prototype、Request、Session等。 - 依赖注入可以通过方法参数实现,Spring会自动寻找匹配的Bean进行注入。
实验案例
简述
构建一个简易的Spring应用,演示如何通过@Configuration
和@Bean
注解创建和注入Bean。创建一个消息服务(MessageService)和一个消息消费者(Consumer),以此来展示依赖注入的工作流程。
实验步骤
步骤1:创建接口和实现类
- MessageService接口:定义一个提供消息的服务接口。
- MessageServiceImpl类:实现上述接口,返回具体的消息内容。
- Consumer类:一个消费消息的类,它将使用
MessageService
。
public interface MessageService {
String getMessage();
}
public class MessageServiceImpl implements MessageService {
@Override
public String getMessage() {
return "Hello from MessageService!";
}
}
public class Consumer {
private final MessageService messageService;
public Consumer(MessageService messageService) {
this.messageService = messageService;
}
public void processMessage() {
System.out.println(messageService.getMessage());
}
}
步骤2:创建配置类
创建一个名为AppConfig
的类,并使用@Configuration
注解标注,以表明它是一个Spring配置类。在这个类中,我们将定义两个方法,分别用@Bean
注解标记,来分别创建MessageService
和Consumer
的Bean。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MessageService messageService() {
return new MessageServiceImpl();
}
@Bean
public Consumer consumer() {
// 注入MessageService到Consumer中
return new Consumer(messageService());
}
}
步骤3:运行和测试
为了运行这个Spring应用并测试Bean的注入,创建一个名为Application
的启动类,使用Spring的AnnotationConfigApplicationContext
来加载AppConfig
配置类,并获取Consumer
Bean,然后调用其processMessage
方法。
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Application {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
Consumer consumer = context.getBean(Consumer.class);
consumer.processMessage();
context.close();
}
}
预期结果
运行Application
主类后,控制台应该输出以下内容:
Hello from MessageService!
这表示MessageService
的Bean已成功注入到Consumer
中,且Consumer
能够使用MessageService
来处理消息,证明了我们通过@Configuration
和@Bean
注解定义的Bean注入是成功的。