//默认 bean id 为方法名 //也可以用 name 指定 @Bean public CompactDisk enyaAlbum(){ returnnew EnyaAlbum(); } @Bean public Player cdPlayer(CompactDisk compactDisk){ returnnew CDPlayer(compactDisk); } }
org.springframework.context.annotation @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) @Documented publicinterfaceProfile extendsannotation.Annotation Indicatesthatacomponentiseligibleforregistrationwhenoneormorespecifiedprofilesareactive. AprofileisanamedlogicalgroupingthatmaybeactivatedprogrammaticallyviaConfigurableEnvironment.setActiveProfilesordeclarativelythroughsettingthespring.profiles.activeproperty, usuallythroughJVMsystemproperties, asanenvironmentvariable, orforwebapplicationsasaServletcontextparameterinweb.xml. The @Profile annotation may be used in any of the following ways: as a type-level annotation on any classdirectlyorindirectlyannotatedwith @Component, including @Configurationclasses asameta-annotation, forthepurposeofcomposingcustomstereotypeannotations asamethod-levelannotationonany @Beanmethod If a @Configuration class is marked with @Profile, all of the @Bean methods and @Import annotations associated with that class will be bypassed unless one or more of the specified profiles are active. This is very similar to the behavior in Spring XML: if the profile attribute of the beans element is supplied e.g., <beans profile="p1,p2">, the beans element will not be parsed unless profiles 'p1' and/or 'p2' have been activated. Likewise, if a @Component or @Configuration class is marked with @Profile({"p1", "p2"}), that class will not be registered/processed unless profiles 'p1' and/or 'p2' have been activated. If a given profile is prefixed with the NOT operator(!), the annotated will be registered if the profile is not active. e.g., for @Profile({"p1", "!p2"}), registration will occur if profile 'p1' is active or if profile 'p2' is not active. If the @Profile annotation is omitted, registration will occur, regardless of which(if any) profiles are active. When defining Spring beans via XML, the "profile" attribute of the <beans> element may be used. See the documentation in spring-beans XSD(version 3.1 or greater)for details.
2.2 条件化的 bean
2.3 歧义性
当有多个 bean 满足自动装配所需的类型时,如何消除歧义
@primary 注解设置首选 bean
各种配置方式中都可以指定
多个类型相同 bean 都指定 @primary, 注入的时候(使用类型)也会带来歧义性
@qualifier 限定某个 bean
@Component 、JavaConfig 的 @bean 组合使用
每个 bean 都可以指定一个限定符,如果没有指定,限定符与 bean id 相同,但如果类的名称(组件扫描)或 bean id 变化时,需要修改注入时指定的限定符;为了避免这种不一致性,可以为 bean 通过 @qualifier("qua1") 指定限定符,注入的时候,也指定相同的限定符即可,这样类的名字和 bean id 就可以随意修改;