spring是一个框架,这个框架可以干很多很多的事情。感觉特别吊。但是,对于初学者来说,很难理解spring到底是干什么的。我刚开始的时候也不懂,后来就跟着敲,在后来虽然懂了,但是依然说不明白它到底是干啥的。看了好多的老师的视频,发现也都不适合小白。于是就想写一篇适合小白看的spring入门,也许可以帮助一部分心学习spring的同学吧。
————扯淡完成
spring到底是个什么东西,这个是我们先放一放,首先,spring是一个可以把我们的对象自动实例化的一个框架,我们今天先演示下这个。我们知道,在我们程序执行的过程中,所有的代码最后运行完都会在内存中有体现的。比如说,我写了如下代码
public class User{
private String userName;
public void setUserName(String userName){
this.userName = userName;
}
public String getUserName(){
return this.userName;
}
}
User user = new User();
当new这句代码执行的时候,我们的user类就加载到内存中去了。而在我们的spring框架中,你只需要引入spring的核心包(百度一下,网上就可以下载),然后在主目录下创建一个applicationContext.xml文件。内容如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
</beans>
然后我们就在里面将我们的User类配置进去。这里的bean的Id就是我们的对象名称。class就是我们的类的全路径。UserName对应的是User类中的属性名称,张三是我们要给它赋的值。代码如下:
1 <beans xmlns="http://www.springframework.org/schema/beans" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/mvc 8 http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.2.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-3.2.xsd "> 15 <bean id ="user" class="com.spring.User"> 16 <property name="userName" value="张三" /> 17 </bean> 18 19 20 </beans>