先说一个下bug
org.xml.sax.SAXParseException: The processing instruction target matching "[xX][mM][lL]" is not allowed.
原因:xml 文件 <?xml version="1.0" encoding="UTF-8"?>前面有空格或者有空行。
一般自己写的xml 文件时不会错,可能在复制,粘贴时候会出错。
bean的作用域
1 sigleton 在每个Spring IOC容器中一个bean定义只有一个对象实例。
配置文件
默认情况下会在容器启动时初始化bean,但我们可以指定bean节点的lazy-init=”true”来延迟初始化bean,这时候,只有第一次获取bean会才初始化bean
<bean id="personService" class="three.spring.service.impl.PersonServiceBean" lazy-init="true"></bean>
所有bean都延迟初始,在根节点beans设置(我觉得翻译成懒惰加栽比较好)(懒惰:能不干就不干,能晚干就晚干)
<beans default-lazy-init="true" .............
2 prototype 每次从容器获取bean都是新的对象
<bean id="personService" class="three.spring.service.impl.PersonServiceBean" scope="prototype"></bean>
3.request
4.session
5.global session
//
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
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-2.5.xsd">
<!--1 -->
<bean id="personService1"
class="four.spring.service.impl.PersonServiceBean"
scope="prototype">
</bean>
<!--1 -->
<bean id="personService2"
class="four.spring.service.impl.PersonServiceBean">
</bean>
</beans>
//
package four.spring.junit;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import four.spring.service.PersonService;
public class SpringTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void instanceSpring() {
// 在类路径下,寻找配置文件,实例化spring容器。
ApplicationContext ctx = new ClassPathXmlApplicationContext("/four/fourbeans.xml");
//配置文件中bean的id,推荐首字母小写 prototype
PersonService personServicePrototype1 = (PersonService)ctx.getBean("personService1");
PersonService personServicePrototype2 = (PersonService)ctx.getBean("personService1");
//判断是不是不是一个对象
if (personServicePrototype1 != personServicePrototype2) {
personServicePrototype1.savePerson();
}
//配置文件中bean的id,推荐首字母小写 sigleton
PersonService personServiceSigleton1 = (PersonService)ctx.getBean("personService2");
PersonService personServiceSigleton2 = (PersonService)ctx.getBean("personService2");
//判断是不是不是一个对象
if (personServiceSigleton1 == personServiceSigleton2) {
personServicePrototype1.savePerson();
}
}
}
//
package four.spring.service;
public interface PersonService {
//面向接口编程,降低耦合度
public abstract void savePerson();
}
//
package four.spring.service.impl;
import four.spring.service.PersonService;
public class PersonServiceBean implements PersonService {
public void savePerson() {
System.out.println("我是包[two.spring.service.impl]的" +
"类[PersonService]的[savePerson]方法");
}
}
//