标签:
1,添加jar包
--springframwork
--commonslogging
2,创建beans.xml文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://www.springframework.org/schema/beans" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"> 6 <!-- 定义一个Bean实例:id为person的java对象,class为改类的路径 --> 7 <bean id="person" class="spr.Person" > 8 <!-- name:调用名为axe的set方法,ref/value指set的参数--> 9 <property name="axe" ref="axe"></property> 10 </bean> 11 </beans>
案例,创建Person类 Axe类,test类
1 package spr; 2 3 public class Person { 4 5 private Axe axe; 6 7 public Axe getAxe() { 8 return axe; 9 } 10 11 public void setAxe(Axe axe) { 12 this.axe = axe; 13 } 14 public void useAxe(){ 15 System.out.print("222"); 16 System.out.print(axe.chop()); 17 } 18 19 }
1 package spr; 2 3 public class Axe { 4 5 public String chop(){ 6 return"111"; 7 } 8 }
1 package spr; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class BeanTest { 7 8 public static void main(String[] args) { 9 // 创建spring容器,获取id为person的bean 10 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); 11 Person p = ctx.getBean("person", Person.class); 12 p.useAxe(); 13 } 14 }
标签:
原文地址:http://www.cnblogs.com/tingbogiu/p/4701701.html