这两个注解一般配合使用。
带有 @Configuration 的注解类表示这个类可以使用 Spring IoC 容器作为 bean 定义的来源。@Bean 注解告诉 Spring,一个带有 @Bean 的注解方法将返回一个对象,该对象应该被注册为在 Spring 应用程序上下文中的 bean。
import org.springframework.context.annotation.*;
@Configuration
public class HelloWorldConfig {
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
上面的代码等价于Beans.xml里的配置:
<beans>
<bean id="helloWorld" class="com.sap.HelloWorld" />
</beans>
这个经过了@Configuration修饰的类的作用,相当于ClassPathXmlApplicationContext.
下面是消费代码:
ApplicationContext ctx =
new AnnotationConfigApplicationContext(HelloWorldConfig.class);
HelloWorld helloWorld = ctx.getBean(HelloWorld.class);
helloWorld.setMessage("Hello World!");
helloWorld.getMessage();
这个HelloWorldConfig是被SpringCGLib动态增强过的: