一、xml形式
- 1.spring容器为new ClassPathXmlApplicationContext(“spring.xml”);
- 2.spring.xml用来配置bean的信息
- 3.bean配置: <bean class=“com.learning.UserService” scope=“singleton” lazy-init=“false”></bean>
- 4.扫描包:<component-scan>
- 5.引入外部属性配置文件:<property-placeHolder resource=“xxx.properties”>
- 6.注入基本属性:<property name=“password” value=“${mysql.password}”></property>
- 7.指定其它配置文件:<import resource=“”>
二、javaConfig形式
- 1.spring容器为new AnnotationConfigApplicationContext(SpringConfig.class);
- 2.@Configuration配置类
- 3. bean配置:@Bean、@Scope(“singleton”)、@Lazy(false)
- 4.扫描包:@ComponentScan
- 5.引入外部属性配置文件@PropertySource(“classpath:db.properties”)
- 6.注入基本属性:@Value(“${mysql.password}”)
- 7.指定其它配置文件@Import({配置类})使用比较灵活
三、源码分析
- 1.基于xml形式与javaConfig形式都会加载配置信息,读取配置信息生成BeanDefinition,后面根据BeanDefinition生成Bean的逻辑是一样的,读取配置类都是实现了BeanDefinitionReader接口的两个实现类
- 2.xml形式加载xml、读取xml配置文件,xml的为XmlBeanDefinitionReader(loadBeanDefinitions)
- 3.javaConfig形式加载配置类、javaConfig的为AnnotatedBeanDefinitionReader(this.reader.register(annotatedClasses));
- 3.xml解析配置文件也在loadBeanDefinitions(DefaultBeanDefinitionDocumentReader解析)中
- 4.javaConfig采用BeanDefinitionRegistryPostProcess扩展点(ConfigurationClassParser配置类解析器解析)
- 5.xml解析<bean><import>
- 6.javaConfig解析@Bean、@Component
- 7.解析完之后都会注册为BeanDefinition