@Bean简单理解

To declare a bean in JavaConfig, you write a method that creates an instance of the
desired type and annotate it with  @Bean . For example, the following method declares
the  CompactDisc bean:
@Bean
public CompactDisc sgtPeppers() {
return new SgtPeppers();
}
The @Bean annotation tells Spring that this method will return an object that should
be registered as a bean in the Spring application context
. The body of the method
contains logic that ultimately results in the creation of the bean instance.
By default, the bean will be given an ID that is the same as the  @Bean -annotated
method’s name
. In this case, the bean will be named  compactDisc . If you’d rather it
have a different name, you can either rename the method or prescribe a different
name with the  name attribute:
@Bean(name="lonelyHeartsClubBand")
public CompactDisc sgtPeppers() {
return new SgtPeppers();
}
No matter how you name the bean, this bean declaration is about as simple as they
come. The body of the method returns a new instance of  SgtPeppers . But because it’s
expressed in Java, it has every capability afforded it by the Java language to do almost
anything to arrive at the  CompactDisc that is returned.
Unleashing your imagination a bit, you might do something crazy like randomly
selecting a  CompactDisc from a selection of choices:
@Bean
public CompactDisc randomBeatlesCD() {
int choice = (int) Math.floor(Math.random() * 4);
if (choice == 0) {
return new SgtPeppers();
} else if (choice == 1) {
return new WhiteAlbum();
} else if (choice == 2) {
return new HardDaysNight();
} else {
return new Revolver();
}
}
I’ll let you daydream a bit about all the ways you can exploit the power of Java to pro-
duce a bean from an  @Bean -annotated method. When you’re done, we’ll pick it back up
and look at how you can inject the  CompactDisc bean into the  CDPlayer in JavaConfig.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斜阳雨陌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值