Spring 入门(控制反转IOC、依赖注入DI、Bean的作用范围、Bean的生命周期)

2023-11-07

 

1.什么是框架

框架(Framework)是整个或部分系统的可重用设计,表现为一组抽象构件及构件实例间交互的方法;另一种定义认为,框架是可被应用开发者定制的应用骨架。前者是从应用方面而后者是从目的方面给出的定义。

2. Java中的框架

Struts HiberNate Spring SpringMvc SpringBoot

 3. Struts2

Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互

4. HiberNate

  1. 开源的对象关系映射框架

  2. 对jdbc的封装的框架

  3. 与pojo(JavaBean)建立映射关系

5. Spring

应用于web层的框架

JavaBean的管理

6. Java企业级开发的演化

  1. Servlet + Java Bean

  2. Servlet + Java Bean + Jsp

  3. Struts2 + Spring + HiberNate(SSH)

  4. Spring Mvc + Spring + mybatis(ibatis) (SSM)

  5. Spring Boot(下一代框架 微服务框架)

7. Spring

1. Spring的简介

Spring是分层的JavaSE/EE full-stack(一站式) 轻量级开源框架

分层:

  1. SUN提供的JavaEE的三层结构:web层、业务层(service)、数据访问层(dao)(持久层,集成层)

  2. Struts2是web层基于MVC设计模式框架.

  3. Hibernate是持久的一个ORM的框架.

一站式:

  1. Spring对web层提供的解决方案 : Spring Mvc

  2. Spring对Service层提供的解决方案 : Spring

  3. Spring对Dao层提供的解决方案 : Jdbc Template

常用的解决方案:

1. web (Struts2 SpringMvc)

2.service(Spring)

3.dao(DBUtils HiberNate mybatis Jdbc Template)

创建Spring项目:

依赖关系:

2. Spring的核心

1. IOC(控制反转)

把对象的创建权交给Spring容器

2. AOP(面向切面编程)

是面向对象的功能延伸.不是替换面向对象,是用来解决OOP(面向对象编程)中一些问题.

3. Spring的版本

spring3.x

spring4.x(推荐使用)

4. Spring的优点

  1. 方便解耦 简化开发

    把所有对象的创建交给Spring管理

  2. 支持Aop编程

    解决在OOP中遇到的一些问题

  3. 声明式事务的支持

  4. 方便调试程序

    在spring中有专门的调试模块Spring-Test

  5. 方便继承各种优秀的框架

    Spring对各种主流的框架都提供了支持

  6. Spring对一些比较难用的API都进行了封装,方便了程序猿的使用(邮件 远程调用....)

5. 日志框架

log4j:开源的优秀的日志框架

..........

日志门面:运行这些日志系统的

slf4j

logging (apache的日志门面)

Log log4j = Log log4j = LogFactory.getLog(TestLog.class);

log4j.info("info");

log4j.debug("debug");

log4j.error("error");

 

6. Spring的入门

创建实体类:

package com.ma.spring.demo01;



public class User {

private String name;

private Integer age;



public String getName() {

return name;

}



public void setName(String name) {

this.name = name;

}



public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

@Override

public String toString() {

return "User{" +

"name='" + name + '\'' +

", age=" + age +

'}';

}

}

1. pom依赖

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>



<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-beans</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>



<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-expression</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>



<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>4.3.12.RELEASE</version>

</dependency>





<dependency>

<groupId>commons-logging</groupId>

<artifactId>commons-logging</artifactId>

<version>1.1.3</version>

</dependency>

<dependency>



<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>1.2.12</version>

</dependency>



</dependencies>

2. 创建log4j的配置文件

 

log4j.properties


### direct log messages to stdout ###

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.Target=System.out

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

log4j.rootLogger=debug, stdout

3. 创建Spring的配置文件

在resources目录下创建applicationContext.xml

引入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

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- 把User交给Spring管理-->

<bean id = "user" class = "com.ma.spring.demo01.User"></bean>

</beans>

4. 使用ApplicationContext创建对象

@Test

public void test01(){

//1、创建Spring的工厂对象(BeanFactory ApplicationContext)

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

//2、使用applicationContext.xml内部配置的bean来创建对象

User user = (User) applicationContext.getBean("user");

System.out.println(user);

}

7.ApplicationContext BeanFactory的区别

1.applicationContext继承自BeanFactory

2.在老版本中Spring中使用BeanFactory,在新版本中使用ApplicationContext

3.BeanFactory会在调用getBean时实例化对象,applicationContext会在容器加载的时候实例化对象

 

8.bean中name和id的区别

1.name和id都是用来给Spring管理的对象命名的

2.id遵循的是xml规范(唯一)

3.name可以配置多个(name = “user1,use2,user3”)

4.name可以出现特殊字符,id不可以出现特殊字符

5.一般使用id属性

 

9.属性的注入(DI)

DI:依赖注入 : 在对象的创建过程中给属性赋值

1.按构造器注入

<!--使用构造器注入属性-->

<constructor-arg name="age" value="21"></constructor-arg>

<constructor-arg name="name" value="小王"></constructor-arg>

2.按setter方法注入

<!--setter方法注入 property的name属性值为:setter方法的名字的首字母小写-->

<bean id = "user" class = "com.ma.spring.demo01.User">

<property name="age" value="20"></property>

<property name="name" value="小明"></property>

</bean>

 

开发过程中推荐使用setter方法注入

 

10.IOC和DI的区别

IOC : 把对象的创建权交给容器

DI : 创建对象时注入对象的属性 

 

11.Spring如何管理对象的创建

 

1、使用无参的构造器

<!--默认使用无参的构造器-->

<bean id = "user" class = "com.ma.spring.demo01.User">

</bean>

2、静态工厂实例化

静态工厂类

package com.ma.spring.demo01;



public class UserFactory {

public static User newInstance(){

return new User();

}

}

xml


 

<!--静态工厂创建对象-->

<bean id = "user" class = "com.ma.spring.demo01.UserFactory" factory-method="newInstance"

</bean>

3、实例工厂创建对象

实例工厂类
 

package com.ma.spring.demo01;



public class UserFactory {

public User newInstance(){

return new User();

}

}

xml


!--实例工厂创建对象-->

<bean id = "userFactory" class="com.ma.spring.demo01.UserFactory"></bean>

<bean id="user" factory-bean="userFactory" factory-method="newInstance"></bean>

12.Bean的作用范围

全局创建一个对象

<bean id = "user" class = "com.ma.spring.demo01.User" scope="singleton">

</bean>

调用一次对象创建一个

scope="prototype"


13.Bean的初始化和销毁

package com.ma.spring.demo01;



public class User {

private Integer age;

private String name;

public User(){

System.out.println("构造方法......");

}

public void init(){

System.out.println("初始化方法......");

}

public void destory(){

System.out.println("销毁方法......");

}

public String getName() {

return name;

}



public void setName(String name) {

this.name = name;

}



public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

xml

<bean id = "user" class = "com.ma.spring.demo01.User" scope="singleton" init-method="init" destroy-method="destory">

</bean>

 

容器创建时,会创建配置的Bean的对象,并且执行init()方法

//1、创建Spring的工厂对象(BeanFactory ApplicationContext)

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

//2、使用applicationContext.xml内部配置的bean来创建对象

User user1 = (User) applicationContext.getBean("user");

User user2 = (User) applicationContext.getBean("user");

System.out.println(user1);

System.out.println(user2);

Spring容器销毁的时候执行销毁方法

applicationContext.close();

 

 

14.Bean的生命周期

  1. instantiate bean对象实例化(如果scope="singleton"时,在容器加载时创建实例)

  2. populate properties 封装属性(DI)

  3. 如果Bean实现BeanNameAware 执行 setBeanName

  4. 如果Bean实现BeanFactoryAware 或者 ApplicationContextAware 设置工厂 setBeanFactory 或者上下文对象 setApplicationContext

  5. 如果存在类实现 BeanPostProcessor(后处理Bean) ,执行postProcessBeforeInitialization(aop的底层)

  6. 如果Bean实现InitializingBean 执行 afterPropertiesSet

  7. 调用<bean init-method="init"> 指定初始化方法 init

  8. 如果存在类实现 BeanPostProcessor(处理Bean) ,执行postProcessAfterInitialization

  9. 执行业务处理

  10. 如果Bean实现 DisposableBean 执行 destroy

  11. 调用<bean destroy-method="customerDestroy"> 指定销毁方法 customerDestroy

 

15.DI的复杂注入

 

1.普通的字面量的注入

<bean id = "user" class = "com.ma.spring.demo01.User">

<property name="age" value="20"></property>

<property name="name" value="小明"></property>

</bean>

2.对象注入

<bean id="user" class="com.ma.spring.demo01.User">

<property name="age" value="22"></property>

<property name="name" value="李四"></property>

</bean>

<bean id="orders" class="com.ma.spring.demo01.Orders">

<property name="user" ref="user"></property >

</bean>

测试类

package com.ma.spring.demo01;



import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;



import java.beans.IntrospectionException;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Method;



public class UserTest {

@Test

public void test01() {

//1、创建Spring的工厂对象(BeanFactory ApplicationContext)

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

//2、使用applicationContext.xml内部配置的bean来创建对象

Orders orders = (Orders) applicationContext.getBean("orders");



System.out.println(orders);

//applicationContext.close();

}

@Test

public void test02() throws ClassNotFoundException, IntrospectionException, IllegalAccessException, InstantiationException {

Class clazz = Class.forName("com.ma.spring.demo01.User");

//PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name",clazz);

//System.out.println(propertyDescriptor.getWriteMethod().getName());

Object obj = clazz.newInstance();

for(Method method : clazz.getMethods()){

if(method.getName().startsWith("set")){

System.out.println(method.getName());

}

}



}

}

3.Map的注入

 

<!--注入Map-->

<bean id="user" class="com.ma.spring.demo01.User">

<property name="age" value="30"></property>

<property name="name" value="杰克"></property>

<property name="map">

<map>

<entry key="k1" value="v1"/>

<entry key="k2" value="v2"/>

<entry key="k3" value="v3"/>

</map>

</property>

</bean>

 

4.List的注入


 

<!--注入List-->

<bean id="user" class="com.ma.spring.demo01.User">

<property name="age" value="30"></property>

<property name="name" value="杰克"></property>

<property name="map">

<map>

<entry key="k1" value="v1"/>

<entry key="k2" value="v2"/>

<entry key="k3" value="v3"/>

</map>

</property>

<property name="hobbies">



<list>

<value>Java</value>

<value>Python</value>

<value>PHP</value>

</list>

</property>

</bean>

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring 入门(控制反转IOC、依赖注入DI、Bean的作用范围、Bean的生命周期) 的相关文章

随机推荐

  • 数据结构-单链表交换相邻两个元素-java

    1 递归法 时间复杂度O n 递归的时间复杂度一般看层数 这个层数是n层 每层执行一次操作 所以是O n 原理 把后半部分看成已经反转好的数据 public ListNode reverseAdjoinList ListNode head
  • 运放的PID电路

    PID就是 比例 proportion 积分 integral 导数 derivative 在工程实际中 应用最为广泛的调节器控制规律为比例 积分 微分控制 简称PID控制 又称PID调节 运放的积分电路 运放的微分电路 微分电路的输出端和
  • 【Python机器学习】KNN进行水果分类和分类器实战(附源码和数据集)

    需要源码和数据集请点赞关注收藏后评论区留言私信 KNN算法简介 KNN K Nearest Neighbor 算法是机器学习算法中最基础 最简单的算法之一 它既能用于分类 也能用于回归 KNN通过测量不同特征值之间的距离来进行分类 KNN算
  • 计算梯度的三种方法: 数值法,解析法,反向传播法

    计算梯度的三种方法 数值法 解析法 反向传播法 一个简单的函数 Python f x y z x y z begin equation begin aligned f x y z x y z end aligned end equation
  • [青少年CTF]Misc—Easy by 周末

    更新日期 2022年12月6日 青少年CTF训练平台MIsc Easy部分的WP 有错误请在评论区指出 万分感谢 个人博客 https www st1ck4r top 0x01 bear 考点 与熊论道解密 在线解密 http hi pcm
  • Xor Sum(讲解异或)【字典树】

    Xor Sum 题目链接 点击 Time Limit 2000 1000 MS Java Others Memory Limit 132768 132768 K Java Others Total Submission s 6182 Acc
  • virtualbox 菜单栏不见了---如何调出来

    前几天在想安装Tools增强功能时 发现找不到菜单栏 而自己在VM中已经设置了菜单栏选项 后来发现是自己切换到了无缝模式 这里对菜单栏的设置进行说明 如图所示 此时的Ubantu中不显示菜单栏 可能是因为切换到了无缝或者全屏模式 可以通过快
  • HTML 网页常用标签

    1
  • rocketmq报错rocketmq dynamic library not found/OSError: librocketmq.so: cannot open shared object f

    https blog csdn net weixin 39586584 article details 107185329 ImportError rocketmq dynamic library not found OSError lib
  • vue react 比较

    首先 vue和react 比较 1 个人认为react比vue在学习成本上要高的 react采用jsx语法 每个模板都有自己独立的view层 数据层 vue 模板方面相对于简单 因为我们都会html css js 2 状态管理方面 reac
  • 零基础开发蓝牙设备

    前言 现在几乎每个人的手机都具备蓝牙功能 所以如果你的硬件设备也具备蓝牙通信功能 那么便可以很容易和手机建立通信 从而具备IOT物联网属性 但我们也知道蓝牙Ble 目前已发展到5 2版本 协议极其复杂 并不是所有人都需要去详细了解它 我们更
  • 强连通分量

    点击打开链接
  • imp-00003:oracle error 959 encountered

    imp 00003 oracle error 959 encountered 背景描述 今天imp 导入dmp dmp中有6张表 且均为同一用户的表 其中四张导入成功 还有两张表导入失败 提示 imp 00003 oracle error
  • 集成学习介绍——Random Forest

    随机森林是一个非常直观 理解起来也比较容易的Bagging算法 前面我们介绍过决策树 其最大的一个缺点就是容易过拟合 随机森林则是由若干决策树组成的模型 其思想就是 三个臭皮匠顶个诸葛亮 比如下图 就是由9个决策树组成的一个随机森林 其中6
  • React Native入门(四)——入门小结

    1 js跳转Activity后 按home键再切回应用白屏 解决方案 修改MainActivity或目标Activity启动方式 总之不能全部为SingleTask 2 代码报错修改后无法链接nodejs服务了 解决方案 尝试在nodejs
  • Pytorch 深度学习入门与实践 第二章 pytorch快速入门 (1)

    python常用库及模块 1 文件管理的相关库 os 该模块为操作系统接口模块 提供了一些方便使用操作系统的相关功能函数 在读写文件时比较方便 2 时间和日期 time 该模块为时间的访问和转换模块 提供了各种时间相关的函数 方便时间的获取
  • Git使用手册/Git教程:git push 推送提交本地仓库代码文件到远程仓库

    相关文章 关于验证是否存在ssh配置以及生成SSH Key的方法可以参照文章 Git使用手册 生成SSH Key 关于SSH Key的使用和公钥在gitHub gitLab的配置等 请参考文章 Git使用手册 使用SSH Key及配置SSH
  • 关于知道后序序列和中序序列确定前序序列

    以下是大神的解释 摘自洛谷题解 比较清晰 DEBAFCG EDBFGCA 首先这棵树的根是A 后序排列的最后一个 输出A 然后在中序排列中找到A的位置 发现它左右各有三个点 分别是它的左右子树 把中序排列左边三个点和后序排列的前三个点作为左
  • python 定时器使用教程 apscheduler模块,检查文件夹

    1 简介 apscheduler是python中的任务定时模块 它包含四个组件 触发器 trigger 作业存储 job store 执行器 executor 调度器 scheduler 2 安装 pip install apschedul
  • Spring 入门(控制反转IOC、依赖注入DI、Bean的作用范围、Bean的生命周期)

    1 什么是框架 框架 Framework 是整个或部分系统的可重用设计 表现为一组抽象构件及构件实例间交互的方法 另一种定义认为 框架是可被应用开发者定制的应用骨架 前者是从应用方面而后者是从目的方面给出的定义 2 Java中的框架 Str