@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
下面是@Configuration里的一个例子
@Configuration publicclassAppConfig{ @Bean publicTransferServicetransferService(){ returnnewTransferServiceImpl(); } }这个配置就等同于之前在xml里的配置
<beans> <beanid="transferService"class="com.acme.TransferServiceImpl"/> </beans>@bean也可以依赖其他任意数量的bean,如果TransferService依赖AccountRepository,我们可以通过方法参数实现这个依赖
@Configuration publicclassAppConfig{ @Bean publicTransferServicetransferService(AccountRepositoryaccountRepository){ returnnewTransferServiceImpl(accountRepository); } }任何使用@Bean定义的bean,也可以执行生命周期的回调函数,类似@PostConstructand@PreDestroy的方法。用法如下
publicclassFoo{ publicvoidinit(){ //initializationlogic } } publicclassBar{ publicvoidcleanup(){ //destructionlogic } } @Configuration publicclassAppConfig{ @Bean(initMethod="init") publicFoofoo(){ returnnewFoo(); } @Bean(destroyMethod="cleanup") publicBarbar(){ returnnewBar(); } }默认使用javaConfig配置的bean,如果存在close或者shutdown方法,则在bean销毁时会自动执行该方法,如果你不想执行该方法,则添加@Bean(destroyMethod="")来防止出发销毁方法
你能够使用@Scope注解来指定使用@Bean定义的bean
@Configuration publicclassMyConfiguration{ @Bean @Scope("prototype") publicEncryptorencryptor(){ //... } }spring提供了scope的代理,可以设置@Scope的属性proxyMode来指定,默认是ScopedProxyMode.NO,你可以指定为默认是ScopedProxyMode.INTERFACES或者默认是ScopedProxyMode.TARGET_CLASS。
以下是一个demo,好像用到了(没看懂这块) //anHTTPSession-scopedbeanexposedasaproxy @Bean @SessionScope publicUserPreferencesuserPreferences(){ returnnewUserPreferences(); } @Bean publicServiceuserService(){ UserServiceservice=newSimpleUserService(); //areferencetotheproxieduserPreferencesbean service.setUserPreferences(userPreferences()); returnservice; }默认情况下bean的名称和方法名称相同,你也可以使用name属性来指定
@Configuration publicclassAppConfig{ @Bean(name="myFoo") publicFoofoo(){ returnnewFoo(); } }bean的命名支持别名,使用方法如下
@Configuration publicclassAppConfig{ @Bean(name={"dataSource","subsystemA-dataSource","subsystemB-dataSource"}) publicDataSourcedataSource(){ //instantiate,configureandreturnDataSourcebean... } }有时候提供bean的详细信息也是很有用的,bean的描述可以使用@Description来提供
@Configuration publicclassAppConfig{ @Bean @Description("Providesabasicexampleofabean") publicFoofoo(){ returnnewFoo(); } }本文内容总结:@Bean的用法,定义bean,bean的依赖,接受生命周期的回调,指定bean的scope,使用@Scope注解,@Scopeandscoped-proxy,自定义bean的命名,bean的别名,bean的描述,
原文链接:https://www.cnblogs.com/feiyu127/p/7700090.html