SpringBoot系列:@Configuration
介绍
- @Configuration 的注解类表示这个类可以使用Spring IoC容器作为bean定义的来源
- @Bean 注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean
简单例子
package com.itxiaoer.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author : liuyk
*/
@Configuration
public class ConfigA {
@Bean
public Foo foo() {
return new Foo();
}
}
class Foo {
public void say() {
System.out.println("hello");
}
}
上面例子等价于
<beans>
<bean id="foo" class="com.itxiaoer.demo.Foo" />
</beans>
说明
- 如果未通过@Bean指定bean的名称,则默认与标注的方法名相同
- @Bean注解默认作用域为单例singleton作用域,可通过@Scope(“prototype”)设置为原型作用域
使用
package com.itxiaoer.demo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author : liuyk
*/
public class DemoApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册配置类
context.register(ConfigA.class);
// 刷新容器
context.refresh();
Foo foo = context.getBean(Foo.class);
foo.say();
}
}
@Bean
@Bean注解支持指定任意的初始化和销毁的回调方法,以及指定Bean的ID:
package com.itxiaoer.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author : liuyk
*/
@Configuration
public class ConfigA {
@Bean(initMethod = "init", destroyMethod = "cleanup", value = "foo2")
public Foo foo2() {
return new Foo();
}
}
class Foo {
public void say() {
System.out.println("hello foo");
}
public void init() {
}
public void cleanup() {
}
}
@Import
@import 注解允许从另一个配置类中加载@Bean定义
package com.itxiaoer.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
* @author : liuyk
*/
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public Bar bar() {
return new Bar();
}
}
class Bar {
public void say() {
System.out.println("hello bar");
}
}
当实例化上下文时,不需要同时指定 ConfigA.class 和 ConfigB.class,只有 ConfigB 类需要提供
package com.itxiaoer.demo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author : liuyk
*/
public class DemoApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 注册配置类
context.register(ConfigB.class);
// 刷新容器
context.refresh();
Foo foo = context.getBean(Foo.class);
foo.say();
}
}
完整代码:https://github.com/liuyukuai/demo-spring-cloud/tree/master/demo-spring-boot-configuration