标签:
1、通过在xml中配置,并且通过bean的存取方法进行注入。
<bean id="jack" class="com.test.pro.Singer"> <property name="age" value="20"></property> <property name="name" value="jack"></property> </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); } }
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文件中的变量值要相同!
标签:
原文地址:http://blog.csdn.net/itbuluoge/article/details/44514799