bean的实例化
构造器方式
静态方法方式
普通工厂方式
一般的,默认bean实例化使用的是构造器方式,调用的是无参的构造方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.Model; public class Dog { private String name; private int age; public Dog(){ System.out.println("初始化Dog类"); } public Dog(String name,int age){ this.name=name; this.age=age; System.out.println("这是有参数的构造方法"); } public void shou(){ System.out.println("旺旺"); } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public void testContext(){ ApplicationContext ac= new ClassPathXmlApplicationContext("com/test/applicationContext.xml"); Dog dog=(Dog) ac.getBean("dog"); dog.shou(); //System.out.println(dog.getName()+" "+dog.getAge()); }
配置让spring容器调用参构造方法,需要在application.xml的对应bean里面配置
<bean id="dog" class="com.Model.Dog" >
<constructor-arg index="0" value="阿旺"></constructor-arg>
<constructor-arg index="1" value="5"></constructor-arg>
</bean>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Test public void testContext(){ ApplicationContext ac= new ClassPathXmlApplicationContext("com/test/applicationContext.xml"); Dog dog=(Dog) ac.getBean("dog"); dog.shou(); System.out.println(dog.getName()+" "+dog.getAge()); }