百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

第二章:Spring的常用配置

bigegpt 2024-09-11 01:11 48 浏览

2.1 Bean的Scope

2.1.1 说明

scope描述的是Spring容器如何新建的实例的。Spring的Scope有几种,通过@Scope注解来实现。

1)Singleton:一个Spring容器中只有一个Bean 的实例,也是Spring的默认配置,全容器共享一个实例。

2)Prototype:每次调用创建一个实例。

3)Request:Web项目中,给每一个http request创建一个Bean实例。

4) Session:Web项目中,给每一个http session创建一个Bean实例。

2.1.2 实例

1)编写Singleton的Bean

package com.dy.spring_demo.ch2.scope;
import org.springframework.stereotype.Service;
/**
* Author:dy_bom
* Description: 单例
* Date:Created in 下午9:59 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Service //默认使用单例 相当于@Scope("singleton)public class DemoSingletonService {}

2)编写prototype的Bean

package com.dy.spring_demo.ch2.scope;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* Author:dy_bom
* Description: 多例
* Date:Created in 下午10:01 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Service@Scope("prototype") // 多例public class DemoPrototypeService {}

3)配置

package com.dy.spring_demo.ch2.scope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Author:dy_bom
* Description: Scope配置
* Date:Created in 下午10:03 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Configuration@ComponentScan("com.dy.spring_demo.ch2.scope")public class ScopeConfig {}

4)运行

package com.dy.spring_demo.ch2.scope;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午10:04 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class Main {
 public static void main(String[] args) {
 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
 DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
 DemoSingletonService s2 = context.getBean(DemoSingletonService.class);
 DemoPrototypeService p1= context.getBean(DemoPrototypeService.class);
 DemoPrototypeService p2= context.getBean(DemoPrototypeService.class);
 System.out.println("单例模式下,s1是否与s2相等:"+s1.equals(s2));
 System.out.println("多例模式下,p1是否与p2相等:"+p1.equals(p2));
 }
}
context.close();

结果如下

单例模式下,s1是否与s2相等:true多例模式下,p1是否与p2相等:false

2.2 Spring EL和资源的调用

2.2.1 说明

Spring EL-Spring表达式语言,支持在xml和注解中使用表达式,类似于JSP的EL表达式语言。

Spring 主要是在注解@Value的参数中使用表达式

2.2.2 实例

1)增加commons-io的依赖

 <properties>
 <commons-io.version>2.5</commons-io.version>
 </properties>
<!--io依赖-->
 <dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>${commons-io.version}</version>
 </dependency>

2)需要注入的Bean

package com.dy.spring_demo.ch2.el;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午10:16 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Servicepublic class DemoElService {
 @Value("其他类型的属性") //注解注入普通字符串
 private String userName; public String getUserName() { return userName;
 } public void setUserName(String userName) { this.userName = userName;
 }
}

3)配置

package com.dy.spring_demo.ch2.el;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午10:18 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Configuration
@ComponentScan("com.dy.spring_demo.ch2.el")
@PropertySource("classpath:com.dy.spring_demo.ch2.el.ElConfig/el.properties") //配置文件
public class ElConfig {
 @Value("普通属性") //注入普通属性
 private String normal; 
 @Value("#{systemProperties['os.name']}") //注入操作系统属性
 private String osName; 
 @Value("#{demoElService.userName}") //注入其他Bean的属性
 private String fromOtherBean; 
 @Value("#{T(java.lang.Math).random() * 100.0}") //注入表达式结果
 private double randomNum; 
 @Value("classpath:com.dy.spring_demo.ch2.el.ElConfig/el.properties") //注入文件资源
 private Resource elFile; 
 @Value("http://www.baidu.com") //注入网络资源
 private Resource baiDuUrl; 
 @Value("${project.author}") //注入配置文件
 private String author; 
 @Autowired
 private Environment environment; //注入环境配置 
 @Bean
 public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
 return new PropertySourcesPlaceholderConfigurer();
 }
 public void outPutResource(){
 try {
 System.out.println(normal);
 System.out.println(osName);
 System.out.println(fromOtherBean);
 System.out.println(randomNum);
 System.out.println(IOUtils.toString(elFile.getInputStream(), Charsets.requiredCharsets().lastKey()));
 System.out.println(IOUtils.toString(baiDuUrl.getInputStream(), Charsets.requiredCharsets().lastKey()));
 System.out.println(author);
 System.out.println(environment.getProperty("project.name"));
 }catch (Exception e){
 e.printStackTrace();
 }
 }
}

4)运行

普通属性
Mac OS X
其他类型的属性
22.75653062028422
project.author = dy_bom
project.name = spring-demo<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"> <input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus> </span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"> </span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif? login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif? login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&") + "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp; <a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>dy_bom
spring-demo

2.3 Bean的初始化和销毁

2.3.1 说明

在开发的过程中,我们经常在Bean的使用之前或者之后有些必要的操作,Spring对Bean的生命周期的操作提供了支持。有如下两种方式:

1)Java的配置方式

使用@Bean的initMethod和destroyMethod。

2)注解方式

利用JSR-250的@PostConstruct和@PreDestroy。

2.3.2 实例

1)增加JSR250支持

 <!--增加JSR-250支持-->
 <dependency>
 <groupId>javax.annotation</groupId>
 <artifactId>jsr250-api</artifactId>
 <version>1.0</version>
 </dependency>

2)使用@Bean形式的Bean

package com.dy.spring_demo.ch2.prepost;
/**
* Author:dy_bom
* Description: @Bean形式的创建和销毁
* Date:Created in 下午10:47 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class BeanWayService {
 public void init(){
 System.out.println("@Bean-init-method");
 } public BeanWayService(){ super();
 System.out.println("初始化构造函数-BeanWayService");
 } public void destroy(){
 System.out.println("@Bean-destroy-method");
 }
}

3)JSR250形式的Bean

package com.dy.spring_demo.ch2.prepost;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午10:50 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class JSR250WayService {
 @PostConstruct //1 在构造函数执行完成之后执行
 public void init(){
 System.out.println("jsr250-init-method");
 } public JSR250WayService(){ super();
 System.out.println("初始化构造函数-JSR250WayService");
 } @PreDestroy //2 在Bean销毁之前执行
 public void destroy(){
 System.out.println("jsr250-destroy-method");
 }
}

4)配置

package com.dy.spring_demo.ch2.prepost;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午10:52 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Configuration@ComponentScan("com.dy.spring_demo.ch2.prepost")public class PrePostConfig {
 @Bean(initMethod = "init",destroyMethod = "destroy") //指定initMethod和destroyMethod方法
 BeanWayService beanWayService(){ return new BeanWayService();
 } @Bean
 JSR250WayService jsr250WayService(){ return new JSR250WayService();
 }
}

5)运行

package com.dy.spring_demo.ch2.prepost;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午10:55 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class Main {
 public static void main(String[] args) {
 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(PrePostConfig.class);
 BeanWayService beanWayService = context.getBean(BeanWayService.class);
 JSR250WayService jsr250WayService = context.getBean(JSR250WayService.class);
 context.close();
 }
}

结果如下:

初始化构造函数-BeanWayService
@Bean-init-method初始化构造函数-JSR250WayServicejsr250-init-methodjsr250-destroy-method@Bean-destroy-method

2.4 Profile

2.4.1 说明

Profile在不同的环境下,提供了不同的配置支持。用如下方法设置profile的激活

1)通过设定Environment的ActiveProfiles来设定当前的context需要使用的配置环境。在开发中使用@Profile注解类或者方法,达到在不同情况下选择实例化的不同的Bean。

2)通过设定的JVM的spring.profiles.active参数来设置环境

3)Web项目设置在Servlet的context.parameter中

2.4.2 实例

1)Bean创建

package com.dy.spring_demo.ch2.profile;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午11:06 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class DemoProfileBean {
 private String content; public String getContent() { return content;
 } public void setContent(String content) { this.content = content;
 } public DemoProfileBean(String content) { this.content = content;
 }
}

2)配置

package com.dy.spring_demo.ch2.profile;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午11:07 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Configurationpublic class ProfileConfig {
 @Bean
 @Profile("dev") public DemoProfileBean devProfileBean(){ return new DemoProfileBean("from development profile");
 } @Bean
 @Profile("prod") public DemoProfileBean prodProfileBean(){ return new DemoProfileBean("from production profile");
 }
}

3)运行

package com.dy.spring_demo.ch2.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午11:09 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class Main {
 public static void main(String[] args) {
 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
 context.getEnvironment().setActiveProfiles("dev"); //开发环境配置文件激活
 context.register(ProfileConfig.class);
 context.refresh();
 DemoProfileBean demoProfileBean = context.getBean(DemoProfileBean.class);
 System.out.println(demoProfileBean.getContent());
 context.close();
 }
}

结果

from development profile

2.5 事件

2.5.1 说明

Spring的事件为Bean和Bean之间的消息通信提供了支持。当一个Bean处理完一个任务之后,希望另一个Bean知道并能做相应的处理,这时,我们需要让另一个Bean监听当前Bean所发送的事件。

流程如下:

1)自定义事件,继承ApplicationEvent。

2)定义事件监听器,实现ApplicationListener。

3)使用容器发布事件。

2.5.2 实例

1)自定义事件

package com.dy.spring_demo.ch2.event;
import org.springframework.context.ApplicationEvent;
/**
* Author:dy_bom
* Description: 自定义事件
* Date:Created in 下午11:20 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class DemoEvent extends ApplicationEvent {
 private String msg; public DemoEvent(Object source, String msg) { super(source); this.msg = msg;
 } public String getMsg() { return msg;
 } public void setMsg(String msg) { this.msg = msg;
 }
}

2)监听

package com.dy.spring_demo.ch2.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* Author:dy_bom
* Description: 监听
* Date:Created in 下午11:22 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Componentpublic class DemoListener implements ApplicationListener<DemoEvent> {
 @Override
 public void onApplicationEvent(DemoEvent event) {
 String msg = event.getMsg();
 System.out.println("我是监听器,我接受到了发布的消息:"+msg);
 }
}

3)发布

package com.dy.spring_demo.ch2.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
/**
* Author:dy_bom
* Description: 发布
* Date:Created in 下午11:25 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Componentpublic class DemoPublisher {
 @Autowired
 private ApplicationContext context; /**
 * 发布消息
 * @param msg
 */
 public void publish(String msg){
 context.publishEvent(new DemoEvent(this,msg));
 }
}

4)配置

package com.dy.spring_demo.ch2.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午11:26 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/@Configuration@ComponentScan("com.dy.spring_demo.ch2.event")public class EventConfig {}

5)运行

package com.dy.spring_demo.ch2.event;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Author:dy_bom
* Description:
* Date:Created in 下午11:27 2018/4/1
* Copyright (c) xdy_0722@sina.com All Rights Reserved.
*/public class Main {
 public static void main(String[] args) {
 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
 DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
 demoPublisher.publish("Hello,dy_bom! This is a application event.");
 context.close();
 }
}

结果如下:

我是监听器,我接受到了发布的消息:Hello,dy_bom! This is a application event.

相关推荐

得物可观测平台架构升级:基于GreptimeDB的全新监控体系实践

一、摘要在前端可观测分析场景中,需要实时观测并处理多地、多环境的运行情况,以保障Web应用和移动端的可用性与性能。传统方案往往依赖代理Agent→消息队列→流计算引擎→OLAP存储...

warm-flow新春版:网关直连和流程图重构

本期主要解决了网关直连和流程图重构,可以自此之后可支持各种复杂的网关混合、多网关直连使用。-新增Ruoyi-Vue-Plus优秀开源集成案例更新日志[feat]导入、导出和保存等新增json格式支持...

扣子空间体验报告

在数字化时代,智能工具的应用正不断拓展到我们工作和生活的各个角落。从任务规划到项目执行,再到任务管理,作者深入探讨了这款工具在不同场景下的表现和潜力。通过具体的应用实例,文章展示了扣子空间如何帮助用户...

spider-flow:开源的可视化方式定义爬虫方案

spider-flow简介spider-flow是一个爬虫平台,以可视化推拽方式定义爬取流程,无需代码即可实现一个爬虫服务。spider-flow特性支持css选择器、正则提取支持JSON/XML格式...

solon-flow 你好世界!

solon-flow是一个基础级的流处理引擎(可用于业务规则、决策处理、计算编排、流程审批等......)。提供有“开放式”驱动定制支持,像jdbc有mysql或pgsql等驱动,可...

新一代开源爬虫平台:SpiderFlow

SpiderFlow:新一代爬虫平台,以图形化方式定义爬虫流程,不写代码即可完成爬虫。-精选真开源,释放新价值。概览Spider-Flow是一个开源的、面向所有用户的Web端爬虫构建平台,它使用Ja...

通过 SQL 训练机器学习模型的引擎

关注薪资待遇的同学应该知道,机器学习相关的岗位工资普遍偏高啊。同时随着各种通用机器学习框架的出现,机器学习的门槛也在逐渐降低,训练一个简单的机器学习模型变得不那么难。但是不得不承认对于一些数据相关的工...

鼠须管输入法rime for Mac

鼠须管输入法forMac是一款十分新颖的跨平台输入法软件,全名是中州韵输入法引擎,鼠须管输入法mac版不仅仅是一个输入法,而是一个输入法算法框架。Rime的基础架构十分精良,一套算法支持了拼音、...

Go语言 1.20 版本正式发布:新版详细介绍

Go1.20简介最新的Go版本1.20在Go1.19发布六个月后发布。它的大部分更改都在工具链、运行时和库的实现中。一如既往,该版本保持了Go1的兼容性承诺。我们期望几乎所...

iOS 10平台SpriteKit新特性之Tile Maps(上)

简介苹果公司在WWDC2016大会上向人们展示了一大批新的好东西。其中之一就是SpriteKitTileEditor。这款工具易于上手,而且看起来速度特别快。在本教程中,你将了解关于TileE...

程序员简历例句—范例Java、Python、C++模板

个人简介通用简介:有良好的代码风格,通过添加注释提高代码可读性,注重代码质量,研读过XXX,XXX等多个开源项目源码从而学习增强代码的健壮性与扩展性。具备良好的代码编程习惯及文档编写能力,参与多个高...

Telerik UI for iOS Q3 2015正式发布

近日,TelerikUIforiOS正式发布了Q32015。新版本新增对XCode7、Swift2.0和iOS9的支持,同时还新增了对数轴、不连续的日期时间轴等;改进TKDataPoin...

ios使用ijkplayer+nginx进行视频直播

上两节,我们讲到使用nginx和ngixn的rtmp模块搭建直播的服务器,接着我们讲解了在Android使用ijkplayer来作为我们的视频直播播放器,整个过程中,需要注意的就是ijlplayer编...

IOS技术分享|iOS快速生成开发文档(一)

前言对于开发人员而言,文档的作用不言而喻。文档不仅可以提高软件开发效率,还能便于以后的软件开发、使用和维护。本文主要讲述Objective-C快速生成开发文档工具appledoc。简介apple...

macOS下配置VS Code C++开发环境

本文介绍在苹果macOS操作系统下,配置VisualStudioCode的C/C++开发环境的过程,本环境使用Clang/LLVM编译器和调试器。一、前置条件本文默认前置条件是,您的开发设备已...