什么是Spring框架
The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform.
A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.
———— 以上内容来自官网
传统的J2EE框架
传统的J2EE框架,结构复杂,内容繁琐,2003年:Rod Johnson发行《J2EE Development without EJB》一书,公开向Sun宣战:EJB中有很多过度工程(over-engineered),需要简化;大多数的企业项目开发 不需要EJB(Enterprise Java Bean)
Spring的定位:Don't Reinvent the Wheel(不要重复发明轮子)
Spring框架
Spring 框架是 Java 应用最广的框架,他是一个轻量级的DI(Dependency Injection,依赖注入)/IoC(Inversion of Control,控制反转) 和 AOP(Aspect Oriented Programming,面向切面编程) 容器的开源框架。Spring 提倡以“最少侵入”的方式来管理应用中的代码,这意味着我们可以随时安装或者卸载 Spring。Spring的使命是简化Java开发。
- Data Access/Integration层包含有JDBC、ORM、OXM、JMS和Transaction模块。
- Web层包含了Web、Web-Servlet、WebSocket、Web-Porlet模块。
- AOP模块提供了一个符合AOP联盟标准的面向切面编程的实现。
- Core Container(核心容器):包含有Beans、Core、Context和SpEL模块。
- Test模块支持使用JUnit和TestNG对Spring组件进行测试。
为什么要用Spring
Spring的优势
- 低侵入 / 低耦合 (降低组件之间的耦合度,实现软件各层之间的解耦)
- 声明式事务管理(基于切面和惯例)
- 方便集成其他框架(如MyBatis、Hibernate)
- 降低 Java 开发难度
Spring能帮我们做什么
- 能帮我们根据配置文件创建及组装对象之间的依赖关系。
- 面向切面编程能帮助我们无耦合的实现日志记录,性能统计,安全控制。
- 与第三方数据访问框架(如Hibernate、JPA)无缝集成,而且自己也提供了一套JDBC访问模板来方便数据库访问。能非常简单的帮我们管理数据库事务。
- 提供与第三方Web(如Struts1/2、JSF)框架无缝集成,而且自己也提供了一套Spring MVC框架,来方便web层搭建。
- 能方便的与Java EE(如Java Mail、任务调度)整合,与更多技术整合(比如缓存框架)
怎么使用Spring
1.导包
Spring Framework是个庞大的体系,Spring的下载比较麻烦,可以点击一下链接,直接寻找需要的版本即可https://repo.spring.io/libs-release-local/org/springframework/spring/
把以下包放如项目的lib目录中
- spring-aop-X.X.X.RELEASE.jar
- spring-beans-X.X.X.RELEASE.jar
- spring-context-X.X.X.RELEASE.jar
- spring-core-X.X.X.RELEASE.jar
- spring-expression-X.X.X.RELEASE.jar
- commons-logging.jar
2.建类
public class Cat {
public Cat() {
System.out.println(Cat.class + "::构造方法");
}
public void speak() {
System.out.println("喵");
}
}
3.配置文件
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 构造器方法 -->
<bean id="id_cat" class="club.laobainb1314.p01.Cat" />
</beans>
4.测试
@Test
void test() {
ApplicationContext appc = new ClassPathXmlApplicationContext(XML);
System.out.println("通过class获取");
Cat cat1 = appc.getBean(Cat.class);
cat1.speak();
Cat cat2 = appc.getBean(Cat.class);
cat2.speak();
}