给属性赋值的四种方式

第一种  设置注入

<bean id="emp0" class="com.bean.Employee" >
    <!--第一种  -->
    <property name="name" value="李智恩"></property>
     <property name="age" value="24"></property>
    </bean>

 第二种 键值分开

<bean id="emp1" class="com.bean.Employee" >
    <property name="name" >
    <value>李智恩</value>
    </property>
     <property name="age">
     <value>24</value>
     </property>
    </bean>

 测试类

@Test
	public void creatSpring(){
		//需要通过一个类来加载spring的配置
		String resource = "Spring.xml";
		ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(resource);
		//换了一种方式赋值相当于上面的set方法
		Employee emp=(Employee) ac.getBean("emp1");
		System.out.println(emp);
		
	}

 

第三种 构造器注入

<bean id="emp2" class="com.bean.Employee" >
   <constructor-arg name="name" value="李智恩"></constructor-arg>
   <constructor-arg name="age" value="25"></constructor-arg>
    </bean>

bean类

public Employee(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Employee() {
		
	}

第四种  数组下标

 <!--第四种  -->
    <bean id="emp3" class="com.bean.Employee" >
   <constructor-arg index="0" value="胡歌"></constructor-arg>
   <constructor-arg index="1" value="25"></constructor-arg>
    </bean>

测试类

@Test
	public void creatSpring2(){
		String resource = "Spring.xml";
		ClassPathXmlApplicationContext cs = new ClassPathXmlApplicationContext(resource);
		Object bean = cs.getBean("emp3");
		System.out.println(bean);
	}

注意:名字需要和配置文档名字一致。 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值