Spring作用域為下面五種
request/session/globle session三種作用域為有Http請求時才能使用不然會出錯
request/session/globle session三種作用域為有Http請求時才能使用不然會出錯示範如下
修改applicationContext.xml的作用域
<bean id="helloWorld" class="com.springHello.HelloWorld" scope="session">
<property name="username" value="John"></property>
</bean>
然後執行後會出現錯誤如下
java.lang.IllegalStateException: No Scope registered for scope name 'session'
at
Spring初始化及銷毀
先在主程式撰寫初始化方法
public void init(){
System.out.println("初始化");
}
然後再applicationContex.xml加入init-method="init"
<bean id="helloWorld" class="com.springHello.HelloWorld" init-method="init">
<property name="username" value="John"></property>
</bean>
執行結果為下
十二月 21, 2017 11:12:29 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
資訊: Loading XML bean definitions from class path resource [applicationContext.xml]
初始化
HelloWorld Spring John
如要規定applicationContex.xml的複數bean使用時都要初始化可以在修改這樣就會都做初始化的方法
applicationContex.xml
<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.xsd" default-init-method="init">
<!--配置bean-->
<bean id="helloWorld" class="com.springHello.HelloWorld">
<property name="username" value="John"></property>
</bean>
<bean id="helloWorld2" class="com.springHello.HelloWorld">
<property name="username" value="Mary"></property>
</bean>
</beans>
主程式
//從ClassPath找到資源文件
Resource resource = new ClassPathResource("applicationContext.xml");
//創建Spring容器(BeanFactor)
BeanFactory beanFactory = new XmlBeanFactory(resource);
//從Spring容器中獲取指定名稱對象
//HelloWorld world = (HelloWorld) beanFactory.getBean("helloWorld2");
//HelloWorld world = beanFactory.getBean(HelloWorld.class);
HelloWorld world = beanFactory.getBean("helloWorld",HelloWorld.class);
world.sayHello();
HelloWorld world2 = beanFactory.getBean("helloWorld2",HelloWorld.class);
world2.sayHello();
結果畫面
十二月 21, 2017 11:38:20 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
資訊: Loading XML bean definitions from class path resource [applicationContext.xml]
初始化
HelloWorld Spring John
初始化
HelloWorld Spring Mary