Spring(一)

 我的第一个Spring程序
  目前我所了解的spring主要是为了依赖注入
  通过xml的配置文件,更改Bean的成员变量的值
  在做这个程序的过程中,遇到了一些问题
  首先是导入包比较麻烦
  需要从网上下载Spring的框架jar包,我下载的是4.0版本的,最新的。它本身包含的很多jar包
  在本demo中只是用了两个:core和beans包。
  导入jar 包之后,开始写代码,写完之后,运行发现错误,缺少commons-logging.jar它是在core和beans中调用的包。
  运行之后,仍然有错误,Bean property 'helloword' is not writable or has an invalid setter method.错误
  找了很久错误,发现原来是因为粗心大意,helloBean.java中的成员变量名与<property>中的name不一致。

  好吧,第一个Spring小程序圆满over,yeah!!

public class HelloBean {
	private String welcome;
	private String name;

	public String getWelcome() {
		return welcome;
	}
	public void setWelcome(String welcome) {
		this.welcome = welcome;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="HelloBean" class="springdemo.HelloBean">
	<property name="welcome">
		<value>Hello!</value>
	</property>
	<property name="name">
		<value>snow</value>
	</property>
</bean>

</beans>

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

@SuppressWarnings("deprecation")
public class SDemo1 {
	public static void main(String[] args){
		Resource rs = new ClassPathResource("beans-config.xml");
		BeanFactory factory = new XmlBeanFactory(rs);
		HelloBean hello = (HelloBean)factory.getBean("HelloBean");
		System.out.println(hello.getWelcome()+" "+hello.getName());
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值