Spring Java Configuration是指用配置类来代替spring中的xml配置文件,
总的来说@Configuration相当于xml中的<beans>标签,@Bean相当于xml中的<bean>标签。
@Configuration没什么好说的,表示声明下面要配置bean了。
具体说下@Bean,在官方的文档中有下面一段话,并举了一个例子:
declare a bean, simply annotate a method with the @Bean
annotation. WhenJavaConfig encounters such a method, it will execute that method and registerthe return value as a bean within aBeanFactory
. By default, thebean name will be the same as the method name (seebean naming for details on how to customize this behavior). Thefollowing is a simple example of a@Bean
method declaration:
@Configuration public class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(); } }
For comparison sake, the configuration above is exactly equivalent to thefollowing Spring XML:
<beans> <bean name="transferService" class="com.acme.TransferServiceImpl"/> </beans>其大意是说,@Bean通过注解一个方法来声明一个bean。当JavaConfig遇到此方法时,这个方法会被执行,并且该方法的返回值被被注册到BeanFactory中。默认的情况下,bean的注册名称是方法名称。
后面的两段代码的作用是相同的,只不过一个是java配置类,而另一个是用xml配置的。