spring原理

1、spring框架什么时候被加载?

(1)ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml")执行的时候,

spring容器对象被创建。

(2)同时,applicationContext.xml里面配置的对象被创建到内存中。(内存模型类似于HashMap)。容器利用反射机制创建bean的实例。如下图

2、spring中配置的bean怎样被创建?

3、bean与bean之间的关系怎样维护?

代码结构图:

applicationContext代码

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6 <bean class="com.spring.service.SpringService" id="springService">
 7     <property name="userName" value="lvyf"/>
 8     <property name="tService" ref="testService"></property>
 9 </bean>
10 
11 <bean class="com.spring.service.TestService" id="testService">
12     <property name="pwd" value="123456"/>
13 </bean>
14 </beans>
View Code

SpringService代码

 1 package com.spring.service;
 2 
 3 public class SpringService {
 4     private String userName;
 5     
 6     private TestService tService;
 7     
 8 
 9     public TestService gettService() {
10         return tService;
11     }
12 
13     public void settService(TestService tService) {
14         this.tService = tService;
15     }
16 
17     public String getUserName() {
18         return userName;
19     }
20 
21     public void setUserName(String userName) {
22         this.userName = userName;
23     }
24 
25     
26     
27     public void sayHello() {
28         System.out.println("hello world " + userName);
29         tService.getPasswd();
30     }
31 
32 }
View Code

TestService代码

 1 package com.spring.service;
 2 
 3 public class TestService {
 4     private String pwd;
 5 
 6     public String getPwd() {
 7         return pwd;
 8     }
 9 
10     public void setPwd(String pwd) {
11         this.pwd = pwd;
12     }
13     
14     public void getPasswd(){
15         System.out.println(pwd);
16     }
17 }
View Code

Run代码

 1 package com.run;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.spring.service.SpringService;
 7 
 8 public class Run {
 9     
10     public static void testRun(){
11         //1、创建spring的IOC容器对象
12         @SuppressWarnings("resource")
13         ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-bean.xml");
14         //2、从IOC容器获取spring bean实例
15         //SpringService sService = (SpringService)ac.getBean("springService");
16         SpringService sService = (SpringService)ac.getBean(SpringService.class);
17         //3、调用sayHello方法
18         sService.sayHello();
19     }
20     
21     public static void main(String[] args) {
22         testRun();
23     }
24 }
View Code
原文地址:https://www.cnblogs.com/fubaizhaizhuren/p/4798722.html