Spring中bean的几种注入方式

声明式注入

@Configuration + @Bean

1
2
3
4
5
6
7
@Configuration
public class QuickstartConfiguration {
@Bean
public Person person() {
return new Person();
}
}

@Component + @ComponentScan

1
2
3
@Configuration
@ComponentScan("com.linkedbear.spring.annotation.c_scan")
public class ComponentScanConfiguration

@Import

1
2
@Import({Boss.class, BartenderConfiguration.class})
public @interface EnableTavern

配置式注入

<bean>标签声明

1
<bean id="person" class="com.linkedbear.spring.basic_dl.a_quickstart_byname.bean.Person"/>

编程式注入 BeanDefinition

ImportBeanDefinitionRegistrar

1
2
3
4
5
6
7
public class WaiterRegistrar implements ImportBeanDefinitionRegistrar {

@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
registry.registerBeanDefinition("waiter", new RootBeanDefinition(Waiter.class));
}
}

手动构造 BeanDefinition 注入

1
2
3
4
5
6
7
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

BeanDefinition personDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class)
.addPropertyValue("name", "zhangsan").getBeanDefinition();
ctx.registerBeanDefinition("person", personDefinition);

ctx.refresh();

借助 BeanDefinitionRegistryPostProcessor 注入

1
2
3
4
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
registry.registerBeanDefinition("animalNameSetterPostProcessor",
new RootBeanDefinition(AnimalNameSetterPostProcessor.class));
}