Spring对bean的管理

一.bean的实例化

1.spring通过反射调用类的无参构造方法

在pom.xml文件中导入坐标:

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.29</version></dependency></dependencies>

创建Student类:

public class Student {public Student(){System.out.println("执行student类的无参构造方法");}
}

在Application.xml文件中创建bean(无参):

<?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的创建方式1(无参)===========================--><bean id="student" class="com.apesource.bean.Student"></bean></beans>

2.通过指定工厂创建bean

 创建Student类:

public class Student {public Student(){}
}

在Application.xml文件中创建bean(工厂):

<?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的创建方式2(工厂)===========================--><bean id="student" class="com.apesource.bean.Student"></bean><bean id="factory" class="com.apesource.factory.StudentFactory"></bean></beans>

3.通过指定静态工厂创建bean

创建Student类:

public class Student {public Student(){}
}

在Application.xml文件中创建bean(静态工厂):

<?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的创建方式3(静态工厂)===========================--><bean id="student" class="com.apesource.factory.StudentStaticFactory" factory-method="creartBean"></bean>
</beans>

 测试Test:

public class Test01 {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Student student = (Student) applicationContext.getBean("student");System.out.println(student);}

测试结果如下:

 

 

二.bean的作用域

语法:<bean scope="属性值"></bean>

        属性:

            singleton单例:spring只会为该bean对象只会创建唯一实例(默认)

<!--====================bean的作用域===========================--><bean id="student" class="com.apesource.bean.Student" scope="singleton"></bean>

运行结果:True,只创建一次,所以内存地址相同

public class Test01 {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Student student1 = (Student) applicationContext.getBean("student");Student student2 = (Student) applicationContext.getBean("student");System.out.println(student1==student2);}
}

            prototype多例:每次获取bean,Spring会创建一个新的bean实例

<!--====================bean的作用域===========================--><bean id="student" class="com.apesource.bean.Student" scope="prototype"></bean>

运行结果:false 创建两次,所以内存地址不同

public class Test01 {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Student student1 = (Student) applicationContext.getBean("student");Student student2 = (Student) applicationContext.getBean("student");System.out.println(student1==student2);}
}

            request:每一次HTTP请求,Spring会创建一个新的bean实例

            session:不同的HTTP会话,Spring会创建不同的bean实例

三.bean的生命周期

 实例化:springIOC创建对象,根据配置文件中Bean的定义,利用Java Reflection反射技术创建Bean的实例

        属性赋值:springDI

        初始化:

            1.接口实现(执行InitializingBean初始化方法)

            2.属性实现(执行init-method 自定义初始化方法)

        操作使用

        销毁:

            1.接口实现(执行DisposableBean初始化方法)

            2.属性实现(执行destroy-method自定义初始化方法)

public class Teacher implements InitializingBean, DisposableBean {public void doinit(){System.out.println("初始化(属性)");}public void dodestory(){System.out.println("销毁了(属性)");}public String tname;@Overridepublic void destroy() throws Exception {System.out.println("销毁了(接口)");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("初始化(接口)");}@Overridepublic String toString() {return "Teacher{" +"tname='" + tname + '\'' +'}';}public void setTname(String tname) {System.out.println("属性赋值");this.tname = tname;}public Teacher() {System.out.println("实例化");}
}

Application.xml文件配置:

<bean id="teacher" class="com.apesource.bean.Teacher" init-method="doinit" destroy-method="dodestory"><property name="tname" value="老师"></property></bean>

 测试代码:

public class Test01 {public static void main(String[] args) {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");Teacher teacher = (Teacher) applicationContext.getBean("teacher");System.out.println(teacher);applicationContext.close(); //关闭spring容器}
}

运行结果:

四.bean的自动装配

spring的配置

        1.spring2.5前==xml

        2.spring2.5后==xml+annotation

        3.spring3.0后==annotation+JavaConfig配置类

spring2.5后=xml+annotation

        目的优化一下代码:           

<bean id="" class="" init-method="" destroy-method="" scope=""><property></property><constructor-arg></constructor-arg></bean>

注解:

1.注入类

替换:

<bean id="" class=""></bean>

位置:类

语法:

@Component

        eg:Class User{}

               <bean id="user" class="com.apesource.包.User"></bean>

||等价于||

                @Component

                        Class User{}

        语法:@Component(value="注入容器中的id,如果省略id为类名且首字母小写,value属性名称可以省略")

<context:component-scan base-package=""></context:component-scan>

        含义:扫描所有被@Component注解所修饰的类,注入容器

@Repository=====>注入数据访问层
@Service========>注入业务层
@Controller=====>注入控制层

        以上三个注解与@Component功能语法一致

2.注入基本数据
@Value

        含义:注入基本数据

        替换:<property></property>

        修饰:成员变量或对应的set方法

        语法:@Value("数据内容")

                   @Value("${动态获取}")

        注意:不能单独用必须配合

<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
@Autowired

        语法:@Autowired(required = "true-默认、false、是否必须进行装配")

        修饰:成员变量或对应的set方法

        含义:按照通过set方法进行“类型装配”,set方法可以省略

        注意:

                1.默认是按照类型装配且同set方法

                2.若容器中有一个类型可以与之匹配则装配成功,若没有一个类型可以匹配则报错NoSuchBeanDefinitionException

                3.若容器中有多个类型可以与之匹配,则自动切换为按照名称装配,若名称没有对应,则报错NoUniqueBeanDefinitionException

3.其他注解
@Primary
@Component
@Primary//首选
public class AccountDaoImp2 implements IAccountDao{@Overridepublic void save() {System.out.println("dao2的新增");}
}

        含义:首选项,当类型冲突的情况下,此注解修饰的类被列为首选(备胎扶正)

        修饰:类

        注意:不能单独使用,必须与@Component....联合使用

@Qualifier(value="名称")
@Component("service")
public class AccountServiceImp implements IAccountService {@Autowired@Qualifier(value = "accountDaoImp1")private IAccountDao dao;@Overridepublic void save() {System.out.println("service的新增");dao.save();}
}

        含义:按照名称装配

        修饰:成员变量

        注意:不能单独使用,必须与@Autowired联合使用

@Resource(name="名称")
@Component("service")
public class AccountServiceImp implements IAccountService {@Resource(name="accountDaoImp2")private IAccountDao dao;@Overridepublic void save() {System.out.println("service的新增");dao.save();}
}

        含义:按照名称装配

        修饰:成员变量

        注意:单独使用

@Scope
@Component
@Scope("prototype")
@Scope("singleton")
public class AccountDaoImp2 implements IAccountDao{@Overridepublic void save() {System.out.println("dao2的新增");}
}

        替换:<bean scope="替换"></bean>

        含义:配置类的作用域

        修饰:类

        注意:不能单独使用,必须与@Component....联合使用

        @Scope("prototype")        单例

        @Scope("singleton")        多例

        @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

        @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)

        @PostConstruct:初始化,修饰方法

                替换:<bean init-method=""></bean>

        @PreDestroy:销毁,修饰方法

                替换:<bean destory-method=""></bean>

@PostConstruct
public void doinit(){System.out.println("初始化");
}@PreDestroy
public void dodestory(){System.out.println("销毁了");
}

Spring3.0=====JavaConfig+annonation

此类充当配置类,替代applicationContext.xml文件

spring中的新注解

@Configuration
@Configuration

作用:指定当前类是一个配置类

 细节:当配置类作为AnnotationConfigApplicationContext对象创建的参数时,该注解可以不写。

@ComponentScan
@ComponentScan(basePackages = {"com.apesource"})

作用:用于通过注解指定spring在创建容器时要扫描的包

属性:

        value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包。

                我们使用此注解就等同于在xml中配置了:

        <context:component-scan base-package="com.apesource"></context:component-scan>

 @Bean
 //注入id为方法名teacher类型为Teacher的JavaBean
@Bean
public Teacher teacher(){return new Teacher();
}//注入id为方法名abc类型为Teacher的JavaBean
@Bean(name = "abc")
public Teacher teachers(){return new Teacher();
}//注入id为方法名dao类型为AccountDao的JavaBean
@Bean
public IAccountDao dao(){return new AccountDaoImp1();
}//注入id为方法名time类型为Date的JavaBean
@Bean
public Date time(){return new Date();
}

作用:用于把当前方法的返回值作为bean对象存入spring的容器中

属性:

        name:用于指定bean的id。当不写时,默认值是当前方法的名称

 @Import
@Import(DataSourceConfig.class)

作用:用于导入其他的配置类

属性:

        value:用于指定其他配置类的字节码。

        例子:@Import(SystemSpringConfig.class)

@PropertySource
@PropertySource(value = "classpath:msg.properties")

作用:用于指定properties文件的位置

属性:

        value:指定文件的名称和路径。

        关键字:classpath,表示类路径下

        配合@Value使用

        例子:@PropertySource("classpath:SystemSpringConfig.properties")

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/2660366.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

SEO中的实体:它们是什么以及为什么它们很重要?

从了解搜索历史到区分实体与关键字&#xff0c;真正了解实体是什么&#xff0c;以便获得更有针对性的搜索流量。 关于SEO专业人士应该如何理解&#xff0c;更重要的是&#xff0c;如何利用SEO中的“实体”&#xff0c;存在很多困惑。 我明白这是从哪里来的&#xff0c;尤其是…

BDD - Python Behave 配置文件 behave.ini

BDD - Python Behave 配置文件 behave.ini 引言behave.ini配置参数的类型配置项 behave.ini 应用feature 文件step 文件创建 behave.ini执行 Behave 引言 前面文章 《BDD - Python Behave Runner Script》就是为了每次执行 Behave 时不用手动敲一长串选项&#xff0c;其实还有…

【王爽老师汇编语言】os和计组必备前置知识-学习记录2

1. 应用程序的组成 从汇编语言角度&#xff0c;一个程序分为&#xff1a; 数据段 堆栈段 代码段 扩展段 应用程序从高级语言的角度比如C语言分段&#xff1a; 数据段 代码段 BSS段 栈、堆 我们可以看到一个可执行程序至少包含&#xff1a;代码段数据段BBS段 一般情况下&…

VirtualBox 网络连接配置

这几天为了确认笔记本电脑的ssd磁盘型号&#xff0c;拆开电脑查看了一下&#xff0c;并且拔出来又装回去了&#xff0c;就是这个插拔的动作&#xff0c;导致原本能好好运行的虚拟机&#xff0c;突然启动报错启动不起来了。看了启动日志&#xff0c;显示启动的时候磁盘数据校验出…

Java多线程技术五——单例模式与多线程

1 概述 本章的知识点非常重要。在单例模式与多线程技术相结合的过程中&#xff0c;我们能发现很多以前从未考虑过的问题。这些不良的程序设计如果应用在商业项目中将会带来非常大的麻烦。本章的案例也充分说明&#xff0c;线程与某些技术相结合中&#xff0c;我们要考虑的事情会…

Spring 是如何解决循环依赖问题的方案

文章目录 Spring 是如何解决循环依赖问题的&#xff1f; Spring 是如何解决循环依赖问题的&#xff1f; 我们都知道&#xff0c;如果在代码中&#xff0c;将两个或多个 Bean 互相之间持有对方的引用就会发生循环依赖。循环的依赖将会导致注入死循环。这是 Spring 发生循环依赖…

Linux安装GitLab教程

Linux安装GitLab教程 1、配置yum源 相当于新建一个文件&#xff0c;通过这个文件来安装gitlab vim /etc/yum.repos.d/gitlab-ce.repo 把这些配置粘进去 [gitlab-ce] nameGitlab CE Repository baseurlhttps://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el$releasever/ gp…

NVIDIA GeForce Experience下载更新失败怎么办?

下载的文件会在C:\ProgramData\NVIDIA Corporation\Downloader这个目录下&#xff0c; 打开名字很长的文件夹&#xff0c;在被删除前手动安装即可。

12.27_黑马数据结构与算法笔记Java(补1)

目录 266 活动选择问题 分析 267 活动选择问题 贪心 268 分数背包问题 贪心 269 0-1 背包问题 贪心 270 斐波那契 动态规划 271 斐波那契 动态规划 降维 272 Bellman Ford 动态规划 分析 273 Bellman Ford 动态规划 实现1 274 Bellman Ford 动态规划 实现2 275 Leetco…

微信小程序开发系列-06事件

什么是事件 事件是视图层到逻辑层的通讯方式。事件可以将用户的行为反馈到逻辑层进行处理。事件可以绑定在组件上&#xff0c;当达到触发条件时&#xff0c;就会执行逻辑层中对应的事件处理函数。事件对象可以携带额外信息&#xff0c;如 id, dataset, touches。 事件分类 事…

使用cmake配置matplotlibcpp生成VS项目

https://gitee.com/feboreigns/matplotlibcpp 这篇文章需要一些cmake基础&#xff0c;python基础&#xff0c;visualstudio基础 准备环境 注意如果在VS平台使用必须要手动下载python&#xff0c;不能使用conda里面的&#xff0c;比如3.8版本&#xff0c;因为conda里面没有py…

Understanding Deep Image Representations by Inverting Them(2014)

文章目录 AbstractIntroductionContribution -Summary hh Abstract 从SIFT和视觉词袋到卷积神经网络(cnn)&#xff0c;图像表示几乎是任何图像理解系统的关键组成部分。然而&#xff0c;我们对它们的了解仍然有限。在本文中&#xff0c;我们通过提出以下问题对表征中包含的视觉…

Mybatis行为配置之Ⅱ—结果相关配置项说明

专栏精选 引入Mybatis Mybatis的快速入门 Mybatis的增删改查扩展功能说明 mapper映射的参数和结果 Mybatis复杂类型的结果映射 Mybatis基于注解的结果映射 Mybatis枚举类型处理和类型处理器 再谈动态SQL 文章目录 专栏精选引言摘要正文autoMappingBehaviorautoMappingU…

关于设计模式、Java基础面试题

前言 之前为了准备面试&#xff0c;收集整理了一些面试题。 本篇文章更新时间2023年12月27日。 最新的内容可以看我的原文&#xff1a;https://www.yuque.com/wfzx/ninzck/cbf0cxkrr6s1kniv 设计模式 单例共有几种写法&#xff1f; 细分起来就有9种&#xff1a;懒汉&#x…

【中小型企业网络实战案例 四】配置OSPF动态路由协议

【中小型企业网络实战案例 三】配置DHCP动态分配地址-CSDN博客 【中小型企业网络实战案例 二】配置网络互连互通-CSDN博客 【中小型企业网络实战案例 一】规划、需求和基本配置_大小企业网络配置实例-CSDN博客 配置OSPF 由于内网互联使用的是静态路由&#xff0c;在链路出…

第八章 JPA和缓存

1.JPA 1.1.创建User实体类 public class User {private Integer uId;private String uName;private Integer uGender;private Integer uAge;private String uLoginname;private String uPassword;private Date uBirth;private String uEmail;private String uAddress; } 1.2…

走进电子技术之光敏电阻、电位器、开关

同学们大家好&#xff0c;今天我们继续学习杨欣的《电子设计从零开始》&#xff0c;这本书从基本原理出发&#xff0c;知识点遍及无线电通讯、仪器设计、三极管电路、集成电路、传感器、数字电路基础、单片机及应用实例&#xff0c;可以说是全面系统地介绍了电子设计所需的知识…

Redis 是如何执行的?

文章目录 命令执行流程步骤一&#xff1a;用户输入一条命令步骤二&#xff1a;客户端先将命令转换成 Redis 协议&#xff0c;然后再通过 socket 连接发送给服务器端步骤三&#xff1a;服务器端接收到命令步骤四&#xff1a;执行前准备步骤五&#xff1a;执行最终命令&#xff0…

牛客网SQL训练5—SQL大厂真题面试

文章目录 一、某音短视频1.各个视频的平均完播率2.平均播放进度大于60%的视频类别3.每类视频近一个月的转发量/率4.每个创作者每月的涨粉率及截止当前的总粉丝量5.国庆期间每类视频点赞量和转发量6.近一个月发布的视频中热度最高的top3视频 二、用户增长场景&#xff08;某度信…

idea Spring Boot项目使用JPA创建与数据库链接

1.pom.xml文件中添加依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.mysql</groupId><artifactId>…