编程式创建bean
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
BeanDefinition personDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
ctx.registerBeanDefinition("person", personDefinition);
ctx.refresh();
Person person = ctx.getBean(Person.class);
System.out.println(person);
}
编程式依赖注入
public class ProgrammaticInjectApplication {
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
BeanDefinition personDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class)
.addPropertyValue("name", "老王").getBeanDefinition();
ctx.registerBeanDefinition("laowang", personDefinition);
BeanDefinition catDefinition = BeanDefinitionBuilder.rootBeanDefinition(Cat.class)
.addPropertyValue("name", "咪咪").addPropertyReference("person", "laowang")
.getBeanDefinition();
ctx.registerBeanDefinition("mimi", catDefinition);
ctx.refresh();
Cat cat = ctx.getBean(Cat.class);
System.out.println(cat);
}
}
refresh 方法会触发 单实例bean 的实例化
包扫描器ClassPathBeanDefinitionScanner:
public static void main(String[] args) throws Exception {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
BeanDefinition personDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class)
.addPropertyValue("name", "老王").getBeanDefinition();
ctx.registerBeanDefinition("laowang", personDefinition);
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> {
return metadataReader.getClassMetadata().getSuperClassName().equals(Animal.class.getName());
});
// int count = scanner.scan("com.linkedbear.spring.programmatic.b_di.bean");
Set<BeanDefinition> animalDefinitions = scanner
.findCandidateComponents("com.linkedbear.spring.programmatic.b_di.bean");
animalDefinitions.forEach(definition -> {
MutablePropertyValues propertyValues = definition.getPropertyValues();
String beanClassName = definition.getBeanClassName();
propertyValues.addPropertyValue("name", beanClassName);
propertyValues.addPropertyValue("person", new RuntimeBeanReference("laowang"));
ctx.registerBeanDefinition(Introspector.decapitalize(beanClassName.substring(beanClassName.lastIndexOf("."))), definition);
});
ctx.refresh();
Cat cat = ctx.getBean(Cat.class);
System.out.println(cat);
}
xml配置文件解析器XmlBeanDefinitionReader:
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
reader.loadBeanDefinitions(new ClassPathResource("programmatic/programmatic-components.xml"));
标签:AnnotationConfigApplicationContext,编程,ctx,Cat,personDefinition,new,驱动,IOC,class
From: https://www.cnblogs.com/sjj123/p/16756503.html