阅读完需:约 3 分钟
如何定义一个Bean
@Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。添加的bean的id为方法名
JavaConfig是Spring4.x推荐的配置方式,可以完全替代XML的方式定义。
// 创建一个类,命名为SpringConfiguration
@Configuration
public class SpringConfiguration {
@Bean
public Student student(){
return new Student(11,"jack",22);
}
}
// 使用bean
AnnotationConfigApplicationContext applicationContext
= new AnnotationConfigApplicationContext(SpringConfiguration.class);
Student student = (Student) applicationContext.getBean("student")
System.out.println(student);
// res:
Student(id=11, name=jack, age=22)
相对于XML的使用方式而言,JavaConfig的使用方式基本是同步的
- @Configuration等同于 <beans></beans>
- @Bean等同于 <bean></bean>
- 通过AnnotationConfigApplicationContext来加载JavaConfig
- 方法名student()就等同于中的id,默认方法名就是beanName
@Bean的其他参数
- name属性等同于的name
- initMethod属性等同于的init-method
- destroyMethod属性等同于的destroy-method
- scope这个比较奇怪,不属于@Bean的参数,这是一个单独的注解,使用方式如下
@Bean(name = "stu",autowire = Autowire.BY_TYPE)
@Scope(value = "singleton")
public Student student(){
return new Student(11,"jack",22);
}
更多例子:
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
return new TransferServiceImpl();
}
}
这个配置就等同于之前在xml里的配置
<beans> <bean id="transferService" class="com.acme.TransferServiceImpl"/> </beans>
@bean 也可以依赖其他任意数量的bean,如果TransferService 依赖 AccountRepository,我们可以通过方法参数实现这个依赖
@Configuration
public class AppConfig {
@Bean
public TransferService transferService(AccountRepository accountRepository) {
return new TransferServiceImpl(accountRepository);
}
}
任何使用@Bean定义的bean,也可以执行生命周期的回调函数,类似@PostConstruct and @PreDestroy的方法。用法如下
public class Foo {
public void init() {
// initialization logic
}
}
public class Bar {
public void cleanup() {
// destruction logic
}
}
@Configuration
public class AppConfig {
@Bean(initMethod = "init")
public Foo foo() {
return new Foo();
}
@Bean(destroyMethod = "cleanup")
public Bar bar() {
return new Bar();
}
}
默认使用javaConfig配置的bean,如果存在close或者shutdown方法,则在bean销毁时会自动执行该方法,如果你不想执行该方法,则添加@Bean(destroyMethod=””)来防止出发销毁方法
你能够使用@Scope注解来指定使用@Bean定义的bean
@Configuration
public class MyConfiguration {
@Bean
@Scope("prototype")
public Encryptor encryptor() {
// ...
}
}
自定义bean的命名
默认情况下bean的名称和方法名称相同,你也可以使用name属性来指定
@Configuration
public class AppConfig {
@Bean(name = "myFoo")
public Foo foo() {
return new Foo();
}
}
Bean的别名
@Configuration
public class AppConfig {
@Bean(name = { "dataSource", "subsystemA-dataSource", "subsystemB-dataSource" })
public DataSource dataSource() {
// instantiate, configure and return DataSource bean...
}
}
Bean的描述
有时候提供bean的详细信息也是很有用的,bean的描述可以使用 @Description来提供
@Configuration
public class AppConfig {
@Bean
@Description("Provides a basic example of a bean")
public Foo foo() {
return new Foo();
}
}