作用
在容器中注册一个 Bean
案例
//定义一个配置类
@Configuration
public class AppConfig {
/**
* 在容器中注册一个 bean, 如果 @Bean 没有指定 name,
* 则默认以方法名作为 bean 的名称
* @Bean 支持指定多个别名
*/
@Bean({"user", "user02"})
public User user01() {
return new User("tom", "123");
}
//支持依赖其他 bean
@Bean
public Car car(User user) {
return new Car(user);
}
}
@Test
void contextLoads() {
//根据注解配置类生成 applicationContext
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(AppConfig.class);
User user = (User) applicationContext.getBean("user");
System.out.println(user);
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);
}
Reference