spring-ioc
来源:互联网 发布:知阅小说网_原创小说网 编辑:程序博客网 时间:2024/06/06 00:18
实例化bean的三种方式:
<!-- 默认的 把类添加到spring容器中 --> <bean id="helloWorld" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.HelloWorld"> <!-- 静态工厂 工厂方法是静态的--> <bean id="helloWorld1" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.FactoryClassHelloWorld1" factory-method="getInstance"> </bean> <!-- 实例工厂 --> <bean id="factoryHelloWorld" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.FactoryClassHelloWorld2"> </bean> <bean id="helloWorld2" factory-bean="factoryHelloWorld" factory-method="getInstance"> </bean>
注意
<bean id="helloWorld" class="com.example.vic.test_spring.ioc_di_setter_HelloWorld.HelloWorld" lazy-init="true" scope="prototype" init-method=""> <!--注入属性--> <property name="" value=""></property> </bean>
第一点– 因为ApplicationContext context =
new ClassPathXmlApplicationContext(“applicationContext.xml”);
会加载所有中的类并生成id类的对象。
第二点 lazy-init=”default” 是默认false,不是延迟加载(加载xml同时生成对象), lazy-init=”true” ,会延迟加载,不会加载xml同时生成对象。
第三点–还有个属性scope=“prototype” 他会创造多个bean对象,因为spring容器默认为单类模式,只会创造一个对象。
第四点–执行顺序,
0.启动spring容器
1.创建helloWorld对象
2.setter 方法注入
3.init-method
4. destroy-method 注销时
public class HelloWorld { public HelloWorld() { System.out.println("new instance"); } public void printHelloWorld(){ System.out.println("调用方法"); }}
public class FactoryClassHelloWorld1 { //工厂类静态方法 public static HelloWorld getInstance(){ return new HelloWorld(); }}
public class FactoryClassHelloWorld2 { //工厂类方法 public HelloWorld getInstance(){ return new HelloWorld(); }}
public class Test_mothed { /** * spring容器在默认的情况下使用默认的构造函数创建对象(默认构造函数可写可不写) */ @Test public void testMothed(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld"); helloWorld.printHelloWorld(); } /* * 在spring容器 内部,调用了HelloWorldFactory中的getInstance静态方法 * 而该方法的内容就是创建对象的过程,是由程序员来完成 * */ @Test public void testFactory1(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld1"); helloWorld.printHelloWorld(); } /** * 实例工厂 * 1、spring容器创建一个实例工厂bean * 2、该bean调用了工厂方法getInstance产生对象 */ @Test public void testFactory2(){ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld2"); helloWorld.printHelloWorld(); }}
0 0
- IOC、Spring的IOC
- Spring IoC
- [Spring]IoC
- Spring IOC
- Spring IOC
- spring IOC
- Spring IOC
- Spring IOC
- Spring Ioc
- Spring IoC
- spring ioc
- Spring IOC
- spring IOC
- Spring Ioc
- Spring IoC
- Spring IOC
- Spring IOC
- Spring IoC
- HDU 2255 KM模版题
- sed部分用法备忘
- Python模块学习——os
- Hadoop 通用数据摄取框架 Gobblin
- CentOS 7.x NAT模式上网配置
- spring-ioc
- MySQL5.5主从配置
- 手把手教你如何把java代码,打包成jar文件以及转换为exe可执行文件
- Dom4J生成xml和包含CDATA问题
- Python模块学习——re
- tensorflow从0开始(6)——保存加载模型
- 欢迎使用CSDN-markdown编辑器
- 【通信技术】计算机通信技术复习习题
- 嵌入式LAB 4:Bootloder