【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 stubApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");Singer singer=(Singer)ctx.getBean("jack");singer.singing();}}输出结果:

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

两粒种子,一片森林。

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

相关文章:

你感兴趣的文章:

标签云: