[Spring]例項化bean的方法/bean的作用域/生命週期
阿新 • • 發佈:2019-02-15
例項化方法
類構造器例項化
package com.yiki.bean.imp;
import com.yiki.service.Service;
/*業務bean*/
public class ServiceBean implements Service {
@Override
public void save(){
System.out.println("serviceBean");
}
}
<bean id="service" class="com.yiki.bean.imp.ServiceBean"></bean>
靜態工程方法例項化
package com.yiki.bean.imp; /*工廠方法用來建立bean物件*/ public class ServiceBeanFactory { public static ServiceBean creatBean() { return new ServiceBean(); } }
<!-- [2]靜態工廠 -->
<bean id="serviceFactory" class="com.yiki.bean.imp.ServiceBeanFactory" factory-method="creatBean"></bean>
例項工廠方法例項化
這裡沒有static
public ServiceBean creatBean2() {
return new ServiceBean();
}
<!-- [3]例項化工廠 --> <bean id="serviceFactory2" class="com.yiki.bean.imp.ServiceBeanFactory" ></bean> <bean id="service2" factory-bean="serviceFactory2" factory-method="creatBean2"></bean>
測試用例
package com.yiki.Test; import org.junit.Test; import org.springframework.beans.factory.serviceloader.ServiceFactoryBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.yiki.service.Service; public class TestCfg { @Test public void test1() { String xmlPath = "ApplicationContext.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); //通過介面 Service service = (Service) applicationContext.getBean("service"); service.save(); } @Test public void test2() { String xmlPath = "ApplicationContext.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); Service service = (Service) applicationContext.getBean("serviceFactory"); service.save(); } @Test public void test3() { String xmlPath = "ApplicationContext.xml"; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); Service service = (Service) applicationContext.getBean("service2"); service.save(); } }
bean的作用域
scope="作用域">
singleton
預設,單例
prototype
每次都會返回一個新的物件
bean的生命週期
lazy-init="例項化時機的選擇"
false
不延遲初始化
true
延遲初始化