@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
定义bean
下面是@Configuration里的一个例子
1 @Configuration 2 public classAppConfig { 3 4 @Bean 5 publicTransferService transferService() { 6 return newTransferServiceImpl(); 7 } 8 }
这个配置就等同于之前在xml里的配置
1 <beans> 2 <bean class="com.acme.TransferServiceImpl"/> 3 </beans>
bean的依赖
@bean 也可以依赖其他任意数量的bean,如果TransferService 依赖 AccountRepository,我们可以通过方法参数实现这个依赖
1 @Configuration 2 public classAppConfig { 3 @Bean 4 publicTransferService transferService(AccountRepository accountRepository) { 5 return newTransferServiceImpl(accountRepository); 6 } 7 }
接受生命周期的回调
任何使用@Bean定义的bean,也可以执行生命周期的回调函数,类似@PostConstruct and @PreDestroy的方法。用法如下
1 public classFoo { 2 public voidinit() { 3 //initialization logic 4 } 5 } 6 7 public classBar { 8 public voidcleanup() { 9 //destruction logic 10 } 11 } 12 13 @Configuration 14 public classAppConfig { 15 16 @Bean(initMethod = "init") 17 publicFoo foo() { 18 return newFoo(); 19 } 20 21 @Bean(destroyMethod = "cleanup") 22 publicBar bar() { 23 return newBar(); 24 } 25 }
默认使用javaConfig配置的bean,如果存在close或者shutdown方法,则在bean销毁时会自动执行该方法,如果你不想执行该方法,则添加@Bean(destroyMethod="")来防止出发销毁方法
指定bean的scope
使用@Scope注解
你能够使用@Scope注解来指定使用@Bean定义的bean
1 @Configuration 2 public classMyConfiguration { 3 4 @Bean 5 @Scope("prototype") 6 publicEncryptor encryptor() { 7 //... 8 } 9 }
自定义bean的命名
默认情况下bean的名称和方法名称相同,你也可以使用name属性来指定
1 @Configuration 2 public classAppConfig { 3 4 @Bean(name = "myFoo") 5 publicFoo foo() { 6 return newFoo(); 7 } 8 }
bean的别名
bean的命名支持别名,使用方法如下
1 @Configuration 2 public classAppConfig { 3 4 @Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource"}) 5 publicDataSource dataSource() { 6 //instantiate, configure and return DataSource bean... 7 } 8 }
bean的描述
有时候提供bean的详细信息也是很有用的,bean的描述可以使用 @Description来提供
1 @Configuration 2 public classAppConfig { 3 4 @Bean 5 @Description("Provides a basic example of a bean") 6 publicFoo foo() { 7 return newFoo(); 8 } 9 }