Spring实例化bean的三种方法
转载
1.用构造器来实例化
print?
1. <bean id="hello2" class="com.hsit.hello.impl.ENhello" />
2.使用静态工厂方法实例化
要写一个bean,bean中定义一个静态方法,生成bean,配置factory-method指定静态方法,运行时容器就会自动调用静态方法生成实例
bean
1. package com.hsit.hello.impl;
2.
3. import com.hsit.hello.IHello;
4.
5. public class CHhello implements IHello {
6.
7. private String msg;
8.
9. public void sayHello() {
10. "中文" + msg);
11. }
12.
13. public String getMsg() {
14. return msg;
15. }
16.
17. public void setMsg(String msg) {
18. this.msg = msg;
19. }
20.
21. @Override
22. public String toString() {
23. // TODO Auto-generated method stub
24. return "Chinese";
25. }
26.
27. public static CHhello createInstance() {
28. "jingtai");
29. return new CHhello();
30. }
31. }
配置文件
1. <bean id="hello1" class="com.hsit.hello.impl.CHhello" factory-method="createInstance" lazy-init="true">
2. <!-- setter注入 -->
3. <property name="msg" value="哈哈">
4. </property>
5. </bean>
3.使用实例工厂方法实例化
要写两个bean,一个是要实例化的bean,另一个是工厂bean。容器先实例化工厂bean,然后调用工厂bean配置项factory-method中指定的静态方法,在方法中实例化bean
1. package com.hsit.hello.impl;
2.
3. public class ENhelloFactory {
4.
5. public ENhello createInstance() {
6. "ENhello工厂");
7. return new ENhello();
8. }
9.
10. public ENhelloFactory() {
11. "chuanjian");
12. }
13.
14. }
1. package com.hsit.hello.impl;
2.
3. import com.hsit.hello.IHello;
4.
5. public class ENhello implements IHello {
6.
7. @Override
8. public void sayHello() {
9. // TODO Auto-generated method stub
10. "hello");
11. }
12.
13. @Override
14. public String toString() {
15. // TODO Auto-generated method stub
16. return "我是ENhello";
17. }
18. }
配置文件
1. <bean id="eHelloFactory" class="com.hsit.hello.impl.ENhelloFactory" />
2. <!-- factory-bean填上工厂bean的id,指定工厂bean的工厂方法生成实例,class属性不填 -->
3. <bean id="example" factory-bean="eHelloFactory" factory-method="createInstance"/>
测试代码
1. BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
2.
3. "example");
4. System.out.println(eNhello.toString());
5.
6. "hello1");