Skip to content

第2章 Spring 常用配置

🚀 2.1 Bean的Scope

🚀 2.1.1 点睛

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

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

(2) Prototype: 原型。每次调用新建一个 Bean 的实例。

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

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

(5) GobalSession: 这个只在 portal 应用中有用,给每一个 global http session 新建一个 Bean实例。

另外,在 SpringBatch中还有一个Scope是使用@StepScope,我们将在批处理一节介绍这个 Scope。

本例简单演示默认的 singleton 和 Prototype,分别从 Spring 容器中获得2次 Bean,判断Bean 的实例是否相等。

🚀 2.1.2 示例

(1)编写 Singleton 的 Bean。

java
package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.stereotype.Service;

@Service //1
public class DemoSingletonService {
}

代码解释:

① 默认为 Singleton,相当于@Scope(“'singleton”)。

(2)编写Prototype 的Bean。

java
package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")//1
public class DemoPrototypeService {
}

代码解释:

① 声明 Scope 为 Prototype。

(3)配置类。

java
package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.scope")
public class ScopeConfig {
}

(4)运行。

java
package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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 开发中经常涉及调用各种资源的情况,包含普通文件、网址、配置文件、系统环境变量等,我们可以使用 Spring 的表达式语言实现资源的注入

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

本节演示实现以下几种情况:

  • (1) 注入普通字符;
  • (2) 注入操作系统属性;
  • (3) 注入表达式运算结果;
  • (4) 注入其他Bean 的属性;
  • (5) 注入文件内容;
  • (6) 注入网址内容;
  • (7) 注入属性文件。

🚀 2.2.2 示例

(1) 准备。增加commons-io可简化文件相关操作,本例中使用commons-io将 file 转换成字符串:

xml
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.3</version>
		</dependency>

在 com.wisely.highlight spring4.ch2.el 包下新建 test.txt,内容随意。

在com.wisely.highlight spring4.ch2.el包下新建 test.properties,内容如下:

ini
book.author=wangyunfei
book.name=spring boot

(2) 需被注入的 Bean。

java
package com.wisely.highlight_spring4.ch2.el;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class DemoService {
	@Value("其他类的属性") //1
    private String another;
	public String getAnother() {
		return another;
	}
	public void setAnother(String another) {
		this.another = another;
	}	
}

代码解释:

① 此处为注入普通字符串

(3) 演示配置类。

java
package com.wisely.highlight_spring4.ch2.el;

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;

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.el")
@PropertySource("classpath:com/wisely/highlight_spring4/ch2/el/test.properties")//7
public class ElConfig {	
	@Value("I Love You!") //1
    private String normal;

	@Value("#{systemProperties['os.name']}") //2
	private String osName;
	
	@Value("#{ T(java.lang.Math).random() * 100.0 }") //3
    private double randomNumber;

	@Value("#{demoService.another}") //4
	private String fromAnother;

	@Value("classpath:com/wisely/highlight_spring4/ch2/el/test.txt") //5
	private Resource testFile;

	@Value("http://www.baidu.com") //6 
	private Resource testUrl;

	@Value("${book.name}") //7 
	private String bookName;

	@Autowired
	private Environment environment; //7
	
	@Bean //7
	public static PropertySourcesPlaceholderConfigurer propertyConfigure() {
		return new PropertySourcesPlaceholderConfigurer();
	}

	public void outputResource() {
		try {
			System.out.println(normal);
			System.out.println(osName);
			System.out.println(randomNumber);
			System.out.println(fromAnother);
			
			System.out.println(IOUtils.toString(testFile.getInputStream()));
			System.out.println(IOUtils.toString(testUrl.getInputStream()));
			System.out.println(bookName);
			System.out.println(environment.getProperty("book.author"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	
}

代码解释:

① 注入普通字符串

②注入操作系统属性

③ 注入表达式结果。

④ 注入其他 Bean 属性。

⑤ 注入文件资源。

⑥ 注入网址资源。

⑦ 注入配置文件。

注入配置配件需使用 @PropertySource 指定文件地址,若使用@Value 注入,则要配置一个PropertySourcesPlaceholderConfigurer 的 Bean。

注意,@Value("$ {book.name}")使用的是“$”而不是“#”。注入Properties 还可从 Environment 中获得。

(4) 运行。

java
package com.wisely.highlight_spring4.ch2.el;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {	
	public static void main(String[] args) {
		 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ElConfig.class);
		 ElConfig resourceService = context.getBean(ElConfig.class);
		 resourceService.outputResource();
		 context.close();
	}
}

结果:

I Love You!
Windows 10
26.90752189451604
其他类的属性
测试文件
<!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;浜琁CP璇?030173鍙?&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

spring boot
wangyunfei

2.3 Bean 的初始化和销毁

2.3.1 点睛

2.3.2 演示

2.4 Profile

2.4.1 点睛

2.4.2 演示

2.5 事件(Application Event)

2.5.1 点睛

2.5.2 示例