感觉自己很浮躁,不愿意写文章,在解决问题的过程中,有心得,也不会很认真写一篇文章。在这里,非常感谢我转载过来的文章的那些作者。
前两天,拿起了Sring复习,因为,我发现,确实需要自己看下源代码,熟悉下基本的使用,虽然以前用过。现在又忘记的差不多了。当初学的是看马士兵的视频,还有一个也很棒讲的,还看过一本思科的spring2.5书。应该快10个月了,没有看spring,忘记的差不多了。下面是搞了一个晚上才配置好的。基本配置:
1.下载包
下载地址:http://www.springsource.org/download
现在spring有3.x版本了,但是我还是建议我们使用的是2.x的版本。我觉得,网上的资料2.x比较多,特别是视频,是在不想自己搞了,那么下载好视频,学个一个星期,基本也就会了。
2.提取jar包导入到工程中去
说真的,我搞不清spring的demo到底是哪个,没有hibernate那么清晰,文档也是这样的。很无奈。但是spring的jar包导入还是简单的。图片怎么插入(????)
3.在spring包中,在jetshop的demo找到配置文件
applicationContext.xml
其实我们要的也是他的名字了。
4.创建一个bean
package com.endual.bean;
public class People {
private int id ;
private String name ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5.在配置文件中applicationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?> <!-- - Middle tier application context definition for the image database. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="people" class="com.endual.bean.People"> <property name="id" value="1"/> <property name="name" value="chenwei"></property> </bean> </beans>
注意,id='people' 指代了我们这个bean,独立的,而name就是bean中的参数了。
我们在bean中,要用set的,最好也写上get吧。我们要获取到bean的值。
value就是我们要注入的值了。
6.测试
我要先获取到配置文件,然后将我们注入的值给打印出来。
spring获取配置文件的方法有三个,我印象中是三个吧。下面是其中的一个:
package com.endual.main;
import java.io.FileInputStream;
import java.io.InputStream;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import com.endual.bean.People;
public class MainRun {
public static void main(String[] args) {
// ClassPathXmlApplicationContext factory=new ClassPathXmlApplicationContext("bean.xml");
ApplicationContext context=new FileSystemXmlApplicationContext("src/applicationContext.xml");
People hello = (People)context.getBean("people");
System.out.println(hello.getName());
System.out.println(hello.getId());
//Message message=(Message)context.getBean("proxyFactoryBean");
}
}
打印结果就是
chenwei
1
注意:
spring的话要导入的是log4j相关的包和配置文件。jar包在spring中好难找,我是从strut2中复制过来的。
有人会问这个spring的配置怎么写,其他我在配置文件中有些到了。