Spring创建对象

通过无参构造器

实体类,并且生成set方法

public class Hello {
	private String name;
	public void setName(String name) {
		this.name = name;
	}
	public Hello() {
		System.out.println("我被无参构造器创建了");
	}
	public Hello(String name) {
		System.out.println("我被有参构造器创建了");
		this.name = name;
	}	
	public void show() {
		System.out.println("hello" + name);
	}
}	

xml

<bean name="hello" class="cn.lee.bean.Hello">
      <property name="name" value="张三"/>
 </bean>

测试代码

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");		
Hello hello = (Hello)context.getBean("hello");
hello.show();

输出

我被无参构造器创建了
hello张三

通过带参构造器

xml

 <bean name="hello2" class="cn.lee.bean.Hello">
       <constructor-arg name="name" value="李四"/> 
 </bean>

输出

我被无参构造器创建了
我被有参构造器创建了
hello李四

对象引用

实体类

public class Apple {
	private String color;
public class Hello {
	private String name;
	private Apple hongFuShi;

xml

 
        <bean name="apple" class="cn.lee.bean.Apple">
        	<property name="color" value="red"></property>
        </bean>
        
        <bean name="hello" class="cn.lee.bean.Hello">
        	<property name="name" value="张三"/>
        	<property name="hongFuShi" ref="apple"></property>
        </bean>

输出

我被无参构造器创建了
张三like eating red apple

当然也可以用构造器

<bean name="apple" class="cn.lee.bean.Apple">
        	<property name="color" value="red"></property>
        </bean>
 <bean name="hello2" class="cn.lee.bean.Hello">
        	<constructor-arg name="name" value="李四"/> 
        	<constructor-arg name="hongFuShi" ref="apple"/> 
        </bean>

输出

我被无参构造器创建了
我被有参构造器创建了
李四like eating red apple

通过类型

<bean name="apple" class="cn.lee.bean.Apple">
        	<property name="color" value="red"></property>
        </bean>
  <bean name="hello3" class="cn.lee.bean.Hello">
        	<constructor-arg type="String" value="李四"/> 
        	<constructor-arg type="cn.lee.bean.Apple" ref="apple"/> 
</bean>

输出

我被有参构造器创建了
李四like eating red apple

通过索引

  <bean name="hello4" class="cn.lee.bean.Hello">
        	<constructor-arg index="0" value="李四"/> 
        	<constructor-arg index="1" ref="apple"/> 
 </bean>

猜你喜欢

转载自blog.csdn.net/qq_40392686/article/details/82873821