Spring属性注入和构造器注入、工厂方法注入

bean:

package s.t;

public class Car {
	private Integer id;
	private String color;
	
	
	public Car() {
		super();
	}
	public Car(Integer id, String color) {
		super();
		this.id = id;
		this.color = color;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	@Override
	public String toString() {
		return "Car [id=" + id + ", color=" + color + "]";
	}
	
	
}


spring.xml

<?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-4.0.xsd ">
							
		<bean id="car" class="s.t.Car">   <!-- 属性注入 -->
			<property name="id"> 
				<value>2</value>
			</property>
			<property name="color">
				<value>red</value>
			</property>
		</bean>
		
		<bean id="cc" class="s.t.Car">  <!-- 构造器注入 -->
			<constructor-arg index="0" type="java.lang.Integer">
				<value>3</value>
			</constructor-arg>
			<constructor-arg index="1" type="java.lang.String">
				<value>orange</value>
			</constructor-arg>
		</bean>
		
		<bean id="cb" class="s.t.CarFactory" factory-method="getCar"></bean>  <!--工厂方法注入 -->
</beans>


测试:

package s.t;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class T1 {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("spring/spring.xml");
		Car car = (Car) app.getBean("cc");
		System.out.println(car);

	}

}


id="car"是属性注入,此时需要有无参构造器和setter方法,id="cc" 是构造器注入,通过index和type确定调用的构造器。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值