源码:
执行的代码
public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml"); Hello hello1=(Hello)context.getBean("hello"); Hello hello2=(Hello)context.getBean("hello"); // hello.getMessage(); System.out.println(hello1==hello2); }
Beans.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <bean id="roleAspect" class="com.dy.spring.aop.aspect.RoleAspect"></bean> <aop:config> <aop:pointcut id="roleServiced" expression="execution(public * com.dy.spring.aop.aspect.RoleService.saveMsg(..))" /> <aop:aspect id="role" ref="roleAspect"> <aop:before method="beforeSave" pointcut-ref="roleServiced"/> <aop:after method="afterSave" pointcut-ref="roleServiced"/> <aop:after-returning method="afterReturning" pointcut-ref="roleServiced"/> <aop:after-throwing method="afterThrowing" pointcut-ref="roleServiced"/> </aop:aspect> </aop:config> <bean id="roleService" class="com.dy.spring.aop.aspect.RoleService"></bean> <!-- <bean id="student" class="com.dy.spring.ioc.Student" default-lazy-init="true"> --> <bean id="student" class="com.dy.spring.ioc.Student"> <property name="name" value="jason"></property> </bean> <bean id="hello" class="com.dy.spring.ioc.Hello" scope="prototype"> <property name="message" value="这是一个测试"/> </bean> </beans>
1.产生beanFactory
ApplicationContext context=new ClassPathXmlApplicationContext("Beans.xml");之后,
通过new DefaultListableBeanFactory(getInternalParentBeanFactory());产生beanfactory
2.beanfactory加载配置信息
XmlBeanDefinitionReader加载配置文件Beans.xml
3.初始化Bean
bean初始化具体的方法finishBeanFactoryInitialization
通过singletonObject = singletonFactory.getObject();初始化bean