一、创建实例

工程的结构如下图

创建加载bean的实例

 

1、创建接口

public interface Person {
	
	public void setName(String name);
	
	public String say();
	
}

  

2、创建接口实现

public class PersonImpl implements Person {

	private String name;
	
	public void setName(String name) {
		this.name = name;
		
	}


	public String say() {

		if(null == name){
			return "Nick";
		}
		return "Hello," + name;
	}

}

 

3、引入commons-logging.jar 和spring-asm.jar

4、创建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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       ">
       <bean >
       		<property name="name" value="Tom" />
       </bean>
</beans>

 

5、创建测试类

public class SpringTest {

	public static void main(String[] args) {
		
		
		
		ClassPathResource resource = new ClassPathResource("com/example/spring/beans.xml");
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
		
		reader.loadBeanDefinitions(resource);
		
		Person person = (Person)factory.getBean("person");
		
		System.out.println(person.say());
		
	}
}

 

6、总结:  

 

1、Spring的bean实际上是缓存在CurrentHashMap对象中

2、在创建bean之前,首先需要将该Bean的创建标识定好,表示该bean已经或是即将被创建,为的是增强缓存的效率。

3、根据bean的scope属性来确定是singleton还是propotype等范围,然后创建相应的bean对象

4、通过Java反射来创建Bean的实例,在创建之前检查访问修饰符,如果不是public,则调用setAccessibile(true)来突破Java的语法限制,使得可以通过如私有的构造方法来创建对象。

5、接下来,寻找bean的属性值,完成属性的注入。

6、将所创建出的singleton对象添加到缓存当中,供下次调用使用。

 

相关文章:

  • 2022-12-23
  • 2021-11-27
  • 2021-04-05
  • 2021-06-13
  • 2021-11-20
  • 2021-08-22
  • 2021-04-13
  • 2021-05-16
猜你喜欢
  • 2022-01-04
  • 2021-08-04
  • 2021-09-22
  • 2022-03-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案