1.首先讲IOC bean的加载
1.1懒加载(延时加载)beanFactory(单例模式)
@Test
public void createbean(){
//加载spring.xml配置文件
BeanFactory beanFactory=new XmlBeanFactory(new ClassPathResource("spring.xml"));
//获取users bean对象
user user=(user) beanFactory.getBean("users");
//输出
System.out.println(user);System.out.println(user);
}
1.2及时加载ClassPathXmlApplicationContext
public void demo() throws Exception {
//加载spring.xml文件
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//得到bean对象
user user=(user)applicationContext.getBean("users");
//输出
System.out.println(user);
}
2bean的常用属性
id :用于getbean()方法 id不能为特殊字符 ;
class:创建对象所在类的路径;
name:功能和属性id差不多,可以是特殊字符;
scope:作用域
singleton:默认 在每一个springioc容器中定义对应一个对象实例;
prototype:一个bean对应多个对象实例;
request:在一次HTTP请求中,一个bean对应一个对象实例,每次都会有各自的bean实例,他们根据某个bean定义创建而成,只在web的spring ApplicationContext下有效;
session:在一个HTTP sesion中,一个bean定义一个实例,只在web的spring ApplicationContext下有效;
global-session:global session作用域类似于标准的HTTP Session作用域,不过它仅仅在基于portlet的web应用中才有意义。Portlet规范定义了全局Session的概念,它被所有构成某个portlet web应用的各种不同的portlet所共享。在global session作用域中定义的bean被限定于全局portlet Session的生命周期范围内。
spring.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-4.3.xsd>
<!--创建一个uers的bean-->
<bean id="users" class="com.zx.pojo.user" scope="prototype"></bean
</beans>
3注入
1.value直接赋值
<!--<bean id="users" class="pojo.user" scope="prototype">-->
<!--<property name="uid" value="1"></property>-->
<!--<property name="uname" value="2"></property>-->
<!--<property name="upwd" value="3"></property>-->
<!--</bean>-->
2.集合注入
list
<!--<bean id="lists" class="pojo.lists">-->
<!--<property name="lists">-->
<!--<list>-->
<!--<ref bean="users"></ref>-->
<!--<ref bean="users2"></ref>-->
<!--</list>-->
<!--</property>-->
<!--</bean>-->
map
<!--<bean id="map" class="pojo.map" scope="prototype">-->
<!--<property name="usermap" >-->
<!--<map>-->
<!--<entry key="1" value-ref="users"></entry>-->
<!--<entry key="2" value-ref="users2"></entry>-->
<!--</map>-->
<!--</property>-->
<!--</bean>-->
构造方法注入:(constructor-arg)
<bean id="users" class="pojo.user">
<constructor-arg index="0" value="123456"></constructor-arg>
<constructor-arg index="1" value="密码"></constructor-arg>
<constructor-arg index="2" value="aaaaa"></constructor-arg>
</bean>