淺談springioc實例化bean的三個方法
1.構(gòu)造器
也就是在上一篇講的那個例子,調(diào)用默認(rèn)的無參構(gòu)造函數(shù)
2.靜態(tài)工廠方法
1)創(chuàng)建需要執(zhí)行的方法的類
public class HelloWorld { public HelloWorld(){ System.out.println("aaaa"); } public void hello(){ System.out.println("hello world"); } }
2)創(chuàng)建靜態(tài)工廠
public class HelloWorldFactory { public static HelloWorld getInstance(){ return new HelloWorld(); } }
3)編寫applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 在這個配置中,spring容器要用默認(rèn)的構(gòu)造函數(shù)為HelloWorld創(chuàng)建對象 --> <bean id="helloWorld" class="HelloWorld"></bean> <!-- 采用靜態(tài)工廠方法創(chuàng)建對象 factory-method為工廠方法 --> <bean id="helloWorld2" class="HelloWorldFactory" factory-method="getInstance"></bean> </beans>
4)啟動容器,創(chuàng)建對象,調(diào)用方法
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld world = (HelloWorld)context.getBean("helloWorld2"); world.hello(); }
3.實例工廠方法(略)
以上這篇淺談springioc實例化bean的三個方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot引入Redis報org.springframework.data.redis.core.RedisT
這篇文章主要介紹了SpringBoot引入Redis報org.springframework.data.redis.core.RedisTemplate類找不到錯誤問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09SpringBoot+MinIO實現(xiàn)文件上傳、讀取、下載、刪除的使用示例
本文主要介紹了SpringBoot+MinIO實現(xiàn)文件上傳、讀取、下載、刪除的使用示例,詳細(xì)介紹每個功能實現(xiàn)的步驟和代碼示例,具有一定的參考價值,感興趣的可以了解一下2023-10-10springboot2.0使用Hikari連接池的方法(替換druid)
這篇文章主要介紹了springboot 2.0使用Hikari連接池的方法(替換druid),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12SSH框架網(wǎng)上商城項目第2戰(zhàn)之基本增刪查改、Service和Action的抽取
SSH框架網(wǎng)上商城項目第2戰(zhàn)之基本增刪查改、Service和Action的抽取,感興趣的小伙伴們可以參考一下2016-05-05