2简单的spring项目

1建立一个类Axe,有一个方法

public class Axe {
    public String chop()
    {
    	
    	return "使用斧头砍柴";
    }
}

2.建立一个person类,有一个set方法,一个属性,一个方法

package org.crazyit.app.service;
public class person {
private Axe axe;
public void setAxe(Axe axe){
	
	this.axe=axe;
}
public void useAxe()
{
	System.out.println("我打算去砍点柴火");
	System.out.println(axe.chop());
}
}

3.重要 建立bean.xml文件 注意,bean.xml放在src根目录下面

<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
	<!-- 配置名为person的Bean,其实现类是org.crazyit.app.service.Person类 -->
	<bean id="person" class="org.crazyit.app.service.person">
		<!-- 控制调用setAxe()方法,将容器中axe Bean作为传入参数 -->
		<property name="axe" ref="axe"/>
	</bean>
	<!-- 配置名为axe的Bean,其实现类是org.crazyit.app.service.Axe类 -->
	<bean id="axe" class="org.crazyit.app.service.Axe"/>
	<!-- 配置名为date的Bean,其实现类是java.util.Date类 -->
	<bean id="date" class="java.util.Date"/>
</beans>

创建容器测试

package org.crazyit.app.service;

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

public class personTest {
	public static void main (String[] args)throws Exception{
		
		// 创建Spring容器
ApplicationContext ctx = new
					ClassPathXmlApplicationContext("beans.xml");
				// 获取id为person的Bean
				person p = ctx.getBean("person" , person.class);
				// 调用useAxe()方法
				p.useAxe();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值