我的第一个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主要是为了依赖注入
通过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());
}
}