【spring教程之五】spring通过存取方法注入

1、通过在xml中配置,并且通过bean的存取方法进行注入。

      <bean id="jack" class="com.test.pro.Singer">
      <property name="age" value="20"></property>
      <property name="name" value="jack"></property>
  </bean>

2、bean类

package com.test.pro;

public class Singer {
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	private int age;
	private String name;
	
	public void singing()
	{
		System.out.println(name+"我在唱歌.....,我的年龄是:"+age);
	}
}

3、测试类

package com.test.pro;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
		Singer singer=(Singer)ctx.getBean("jack");
		singer.singing();

		
	}
	
	

}

输出结果:



实际上和构造函数注入的方式很想象,这里要注意一点的地方,就是应该在注入的时候,一定要将bean中property中的name属性值和bean文件中的变量值要相同!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值