2002,Rod johnson 首次推出了Spring框架的前身 interface21框架并于2003年Spring框架以interface21框架为基础,重新设计,发布1.0正式版。
Spring官网:https://spring.io/
SpringGithub地址:https://github.com/spring-projects/spring-framework
Spring官网下载地址:https://repo.spring.io/release/org/springframework/spring/
我们都知道Spring是开源,免费的,而且是一个轻量级、非入侵式的框架。具体点来说:Spring是一个轻量级的控制反转【IOC】和面向切面【AOP】的(容器)框架。
Spring两大特性:
IOC (控制反转)、 AOP(面向切面编程)
我们先使用Spring来编写一段代码看一下:
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.9.RELEASEversion>
dependency>
package com.MLXH.pojo;
public class Hello {
private String name;
public Hello() {
}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Hello,"+name);
}
@Override
public String toString() {
return "Hello{" +
"name='" + name + '\'' +
'}';
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello1" class="com.MLXH.pojo.Hello">
<property name="name" value="Spring"/>
bean>
<bean id="hello2" class="com.kuang.pojo.Hello">
<property name="name" value="SpringFrameWork"/>
bean>
beans>
这样我们将hello类的对象在Spring的bean.xml中配置好了
4. 测试
package com.MLXH.pojo;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test(){
//解析beans.xml配置文件,生产管理相应的Bean对象;
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//通过Bean得到这个对象的实体
Hello hello1 = (Hello)context.getBean("hello1");
hello.show();
System.out.println("======华丽的分割线========")
Hello hello2 = (Hello)context.getBean("hello2");
hello2.show();
}
}
结果:
总结:可以看到,我们使用bean.xml文件就可以获取到Hello类的对象,其对象我们在bean.xml文件中就配置好了,在测试类中直接接受这个对象即可…(emmmmm,目前看起来貌似没啥用,甚至觉得不如直接创建对象来的简单…),接下来会慢慢说到他的强大之处…
扩展
来了解一下Spring配置文件中的一些标签使用及作用
User bean = context.getBean(User.class);
<bean id="user" name="userTwo,user3" class="com.kuang.pojo.User">
<property name="name" value="Spring"/>
bean>
alias:给对象起别名
<alias name="user" alias="user4"/>
import:导入标签
作用:导入另外一个资源,把另外配置文件装进来
<import resource="classpath*:userBeans.xml"/>
<import resource="classpath:userBeans.xml"/>
<import resource="file:"/>
<import resource="http:"/>
import一般在团队项目中会使用,每个人开发各自的beans.xml,最后用一个总的文件拼装起来。