當前位置:
首頁 >
Spring 学习总结 使用静态工厂创建Bean
發布時間:2025/5/22
33
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Spring 学习总结 使用静态工厂创建Bean
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
創建Bean時,class屬性必須指定,此時為靜態工廠類。 factory-method指定靜態工廠方法名。
接口:
| 1 2 3 | public?interface?Being { ????public?void?testBeing(); } |
Dog類
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public?class?Dog?implements?Being{ ????? ????private?String msg; ????public?void?setMsg(String msg) { ????????this.msg = msg; ????} ????@Override ????public?void?testBeing() { ????????System.out.println(msg +?" 狗愛啃骨頭"); ????????? ????} } |
?
Cat類
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public?class?Cat?implements?Being{ ????private?String msg; ????public?void?setMsg(String msg) { ????????this.msg = msg; ????} ????@Override ????public?void?testBeing() { ????????System.out.println(msg +?" 貓愛吃老鼠!"); ????????? ????} } |
Bean里配置
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?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-3.0.xsd"> ????<bean id="dog"?class="com.springtest2.factory.BeingFactory" ????????factory-method="getBeing"> ????????<constructor-arg value="dog"?/> ????????<property name="msg"?value="我是狗"?/> ????</bean> ????<bean id="cat"?class="com.springtest2.factory.BeingFactory" ????????factory-method="getBeing"> ????????<constructor-arg value="cat"?/> ????????<property name="msg"?value="我是貓"?/> ????</bean> </beans> |
調用測試
| 1 2 3 4 5 6 7 8 | private?static?void?testFactory(){ ????ApplicationContext context =?new?ClassPathXmlApplicationContext(new?String[]{"beans_factory.xml"}); ????Being b1 = context.getBean("dog", Being.class); ????b1.testBeing(); ????? ????Being b2 = context.getBean("cat", Being.class); ????b2.testBeing(); } |
輸出結果
本文轉自Work Hard Work Smart博客園博客,原文鏈接:http://www.cnblogs.com/linlf03/p/5604878.html,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的Spring 学习总结 使用静态工厂创建Bean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [译]ASP.NET Core 2.0
- 下一篇: JS组件系列——开源免费图表组件:Cha