认识Spring
1.Spring
是一个从实际开发中抽取出来的框架,企业级应用开发的
“
一站式
”
选择,贯穿表现层、业务层和持久层。具有高开放性,并能与其他框架无缝整合,俗称
“
架构粘合剂
”
。
2.Spring
有两大核心功能:控制反转
/
依赖注入
(
IOC/DI
)
和
面向切面编程
(
AOP
)
3.对于开发者来说,开发者使用
Spring
框架主要是做两件事:①开发
Bean
;②配置
Bean
4.Spring
容器作为超级大工厂,负责创建、管理所有的
Java
对象,这些
Java
对象被称为
Bean
。
使用maven搭建Spring
步骤一 编写HelloSpring
package com.niit.springtest;
public class HelloSpring {
public String who="";
public void hello(){
System.out.println("Hello"+this.who);
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
}
步骤二 添加Spring依赖
<!--Spring 的依赖支持-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.18.RELEASE</version>
</dependency>
步骤三 编写spring的配置文件 ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--创建HelloSpring类的对象-->
<bean id="helloSpring" class="com.niit.springtest.HelloSpring">
<!--给属性who赋值-->
<property name="who" value="SpringTwo"/>
</bean>
</beans>
步骤四 编写测试类调用Spring创建的bean (需要在pom.xml引入junit)
package test;
import com.niit.springtest.HelloSpring;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
@Test
public void testOne(){
//传统方法
HelloSpring helloCommon = new HelloSpring();
helloCommon.who="spring";
helloCommon.hello();
//使用Spring如何调用,创建对象的 不再由java类来处理
// 而是提交给Spring容器来处理
//初始化Spring的上下文
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//通过上下文对象的getbean()方法来,获取指定Id的实例
HelloSpring helloSpring=(HelloSpring)context.getBean("helloSpring");
helloSpring.hello();
}
}
运行结果