package oilprice;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.core.io.ClassPathResource;
import java.util.Arrays;
/**
* @author micro.cloud.fly
* @date 2022/7/15 3:39 下午
* @desc
*/
//演示各种BeanDefinition的来源
public class TestBeanDefinition {
public static void main(String[] args) {
System.out.println("========================>一开始");
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
System.out.println("========================>1)从xml 获取");
XmlBeanDefinitionReader reader1 = new XmlBeanDefinitionReader(beanFactory);
reader1.loadBeanDefinitions(new ClassPathResource("bd.xml"));
System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
System.out.println("========================> 2)从配置类获取");
beanFactory.registerBeanDefinition("config1", BeanDefinitionBuilder.genericBeanDefinition(Config1.class).getBeanDefinition());
ConfigurationClassPostProcessor postProcessor = new ConfigurationClassPostProcessor();
postProcessor.postProcessBeanDefinitionRegistry(beanFactory);
System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
System.out.println("========================>)扫描获取");
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanFactory);
scanner.scan("oilprice.sub");
//会多出来一些spring内置的一些类,是因为包扫描的过程中,spring内部注册的bean
System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
}
class Bean1 {
}
class Bean2 {
}
class Config1 {
@Bean
public Bean2 bean2() {
return new Bean2();
}
}
}
bd.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bean1" class="oilprice.TestBeanDefinition$Bean1"/>
</beans>
Bean3.java
package oilprice.sub;
import org.springframework.stereotype.Component;
/**
* @author micro.cloud.fly
* @date 2022/7/15 3:49 下午
* @desc
*/
@Component
public class Bean3 {
}