@Configuration和@Bean
@Configuration 相当于<beans>
可以用在类,接口(包括注解类型),或者枚举声明上
@Bean 相当于<bean>
,这个只能用在方法或者注解类型声明上
所以
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
就相当于
<beans>
<bean id="myService" class="com.acme.services.MyServiceImpl"/>
</beans>
@Configuration和@Component的区别
在spring-framework的文档里写了
Full @Configuration vs 'lite' @Beans mode?
When @Bean methods are declared within classes that are not annotated with @Configuration
they are referred to as being processed in a 'lite' mode. For example, bean methods declared in
a @Component or even in a plain old class will be considered 'lite'.
Unlike full @Configuration, lite @Bean methods cannot easily declare inter-bean dependencies.
Usually one @Bean method should not invoke another @Bean method when operating in 'lite' mode.
Only using @Bean methods within @Configuration classes is a recommended approach of
ensuring that 'full' mode is always used. This will prevent the same @Bean method from accidentally
being invoked multiple times and helps to reduce subtle bugs that can be hard to track down when
operating in 'lite' mode.