SPRING IN ACTION 第4版笔记-第二章-003-以Java形式注入Bean、@Bean的用法
1.
package soundsystem; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class CDPlayerConfig { @Bean public CompactDisc compactDisc() { return new SgtPeppers(); } @Bean public CDPlayer cdPlayer(CompactDisc compactDisc) { return new CDPlayer(compactDisc); } }
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:
2.可以指定bean名称
@Bean(name="lonelyHeartsClubBand") public CompactDisc sgtPeppers() { return new SgtPeppers(); }
3.利用@Bean根据条件注入不同的依赖
@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(); } }
4.表面上似乎是调用同一个配置文件的函数
@Bean public CDPlayer cdPlayer() { return new CDPlayer(sgtPeppers()); }
这种配置表面上似乎是调用同一个配置文件的函数,但bean默认情况下是单例的,
It appears that the CompactDisc is provided by calling sgtPeppers , but that’s not
exactly true. Because the sgtPeppers() method is annotated with @Bean , Spring will
intercept any calls to it and ensure that the bean produced by that method is returned
rather than allowing it to be invoked again.
5.spring会自动找id为“compactDisc”的bean注入
@Bean public CDPlayer cdPlayer(CompactDisc compactDisc) { return new CDPlayer(compactDisc); }
6.不但可以通过构造函数,也可通过set访求注入
@Bean public CDPlayer cdPlayer(CompactDisc compactDisc) { CDPlayer cdPlayer = new CDPlayer(compactDisc);//这里的构造函数是不是不用传参数???? cdPlayer.setCompactDisc(compactDisc); return cdPlayer; }