當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 学习总结 使用静态工厂创建Bean
生活随笔
收集整理的這篇文章主要介紹了
Spring 学习总结 使用静态工厂创建Bean
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
創(chuàng)建Bean時,class屬性必須指定,此時為靜態(tài)工廠類。 factory-method指定靜態(tài)工廠方法名。
接口:
| 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> |
調(diào)用測試
| 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(); } |
輸出結(jié)果
本文轉(zhuǎn)自Work Hard Work Smart博客園博客,原文鏈接:http://www.cnblogs.com/linlf03/p/5604878.html,如需轉(zhuǎn)載請自行聯(lián)系原作者
總結(jié)
以上是生活随笔為你收集整理的Spring 学习总结 使用静态工厂创建Bean的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [译]ASP.NET Core 2.0
- 下一篇: ASP.NET MVC Controll