修真院java后端工程师学习课程--任务1(day four)
今天学习的是spring框架,内容主要有:
spring的概念,主要是做什么的:
Spring是一个基于IOC和AOP的结构J2EE系统的框架
IOC 反转控制 是Spring的基础,Inversion Of Control
简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象
DI 依赖注入 Dependency Inject. 简单地说就是拿到的对象的属性,已经被注入好相关值了,直接使用即可。
Spring 内容:IOC容器 控制反转。
Aop实现 面向切面编程
数据访问支持 1 简化jdbc/orm框架
2 声明式事务
1. Spring容器的主要目的:降低业务逻辑层和其他层的耦合度(IOC)
2. Spring容器 用来创建和管理(管理对象和对象之间的关系)程序中的所有对象的实例
3. 非侵入式框架轻量级开源框架
Spring的核心 ( IOC ,AOP )
IOC(Inversin Of Control) 控制反转
在没有使用框架之前我们都是在Service 层创建dao的实例对象!控制权在service !
现在我们使用了Spring框架,创建dao的实例对象—使用Spring容器 控制权在 Spring容器!
这种控制权从程序的代码中转到Spring容器的行为就称为 IOC 控制反转
学习完spring的概念作用后动手做一个实例:
步骤1:下载spring的jar包
地址:https://pan.baidu.com/s/1o9nqDxK
步骤2:在eclipse下新建一个java project命名为spring
步骤3:jar包的导入
把jar包导入到项目中,导包办法:右键 project->properties->java build path->libaries->add external jars
步骤4;新建pojo
准备pojo Category,用来演示IOC和DI
- package com.how2java.pojo;
- public class Category {
- 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;
- }
- private int id;
- private String name;
- }
步骤5.applicationContext.xml
在src目录下新建applicationContext.xml文件
applicationContext.xml是Spring的核心配置文件,通过关键字c即可获取Category对象,该对象获取的时候,即被注入了字符串”category 1“到name属性中
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean name="c" class="com.how2java.pojo.Category">
- <property name="name" value="category 1" />
- </bean>
- <bean name="p" class="com.how2java.pojo.Product">
- <property name="name" value="product1" />
- <property name="category" ref="c" />
- </bean>
- </beans>
步骤6:Testspring
- package com.how2java.test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.how2java.pojo.Product;
- public class TestSpring {
- public static void main(String[] args) {
- ApplicationContext context = new ClassPathXmlApplicationContext(
- new String[] { "applicationContext.xml" });
- Product p = (Product) context.getBean("p");
- System.out.println(p.getName());
- System.out.println(p.getCategory().getName());
- }
- }
步骤7:运行程序