Spring Boot实战(2) Spring常用配置

时间:2023-03-09 04:46:26
Spring Boot实战(2) Spring常用配置

1. Bean的Scope

scope描述Spring容器如何新建Bean的实例。通过注解@Scope实现,取值有:

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

b. Prototype:每次调用新建一个Bean的实例

c. Request:Web项目中,给每一个Http Request新建一个Bean实例

d. Session:Web项目中,给每一个Http Session新建一个Bean实例

e. GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个Bean实例。

示例:演示Singleton和Prototype分别从Spring容器中获取2次Bean,判断Bean的实例是否相等

1) 编写Singleton的Bean

 package com.ws.study.scope;

 import org.springframework.stereotype.Service;

 // 默认为Singleton,等同于@Scope("singleton")
@Service
public class DemoSingletonService {
}

2) 编写Prototype的Bean

 package com.ws.study.scope;

 import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service; @Service
// 声明为Prototype
@Scope(value = "prototype")
public class DemoPrototypeService {
}

3) 配置类

 package com.ws.study.scope;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component; @Component
@ComponentScan("com.ws.study.scope")
public class ScopeConfig {
}

4) 运行类

 package com.ws.study.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);
System.out.println("s1与s2是否相等:"+s1.equals(s2)); DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);
System.out.println("p1与p2是否相等:"+p1.equals(p2));
} }

5) 运行结果

 五月 30, 2018 11:13:15 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@183da3f: startup date [Wed May 30 23:13:15 CST 2018]; root of context hierarchy
s1与s2是否相等:true
p1与p2是否相等:false
五月 30, 2018 11:13:15 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@183da3f: startup date [Wed May 30 23:13:15 CST 2018]; root of context hierarchy

2. Spring EL和资源调用

Spring EL为Spring表达式语言,支持在xml和注解中使用表达式。Spring EL实现普通文件、网址、配置文件、系统环境变量等资源的注入。Spring主要在@Value的参数中使用表达式。

示例:

1) 加入commons-io依赖

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

2) 包下创建text.txt,内容随意,此示例写入如下:

 Spring

3) 包下新建test.properties

 test.content=spring
test.date=2018

4) 需被注入的Bean

 package com.ws.study.el;

 import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; @Service
public class DemoService {
// 注入普通字符串
@Value("其他类的属性")
private String another; public String getAnother() {
return another;
} public void setAnother(String another) {
this.another = another;
}
}

5) 配置类

 package com.ws.study.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.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component; @Component
@ComponentScan("com.ws.study.el")
// 注入加载的配置文件
@PropertySource("classpath:com/ws/study/el/test.properties")
public class ElConfig { // 注入普通字符串
@Value("I love you")
private String normal; // 注入操作系统属性
@Value("#{systemProperties['os.name']}")
private String osName; // 注入表达式结果
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber; // 注入其他Bean属性
@Value("#{demoService.another}")
private String fromAnother; // 注入文件资源
@Value("classpath:com/ws/study/el/test.txt")
private Resource testFile; // 注入Url
@Value("https://www.baidu.com")
private Resource testUrl; // 注入配置文件
// 如果没有上述的@PropertySource,而使用需要@Value加载配置文件,则需配置一个PropertySourcesPlaceholderConfigurer的Bean
@Value("${test.content}")
private String content; // 注入配置文件也可以从Environment获取
@Autowired
private Environment environment; @Bean
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(content);
System.out.println(environment.getProperty("test.content"));
} catch (Exception e) {
}
}
}

6) 运行类

 package com.ws.study.el;

 import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

7) 运行结果

 五月 31, 2018 10:04:31 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1bc7afb: startup date [Thu May 31 22:04:31 CST 2018]; root of context hierarchy
I love you
Windows 7
81.51080310192492
其他类的属性
Spring
<!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=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/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=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://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> spring
spring
五月 31, 2018 10:07:34 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1bc7afb: startup date [Thu May 31 22:04:31 CST 2018]; root of context hierarchy

3. Bean的初始化和销毁

(1) Spring对Bean的生命周期的操作提供了支持。对于Java配置方式,使用@Bean的initMethod和destroyMethod(相当于xml配置的init-method和destory-method);对于注解方式,使用JSR-250的@PostConstruct和@PreDestroy

示例:

1) 增加JSR250支持

 		<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>

2) 使用@Bean形式的Bean

 package com.ws.study.prepost;

 public class BeanWayService {

 	public void init(){
System.out.println("@Bean-init-method");
} public BeanWayService(){
super();
System.out.println("初始化构造函数-BeanWayService");
} public void destory(){
System.out.println("@Bean-destroy-method");
}
}

3) 使用JSR250形式的Bean

 package com.ws.study.prepost;

 import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; public class JSR250WayService { // 在构造函数执行完之后执行
@PostConstruct
public void init(){
System.out.println("jsr250-init-method");
} public JSR250WayService(){
super();
System.out.println("初始化构造函数-JSR250WayService");
} // 在Bean销毁之前执行
@PreDestroy
public void destroy(){
System.out.println("jsr250-destroy-method");
}
}

4) 配置类

 package com.ws.study.prepost;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan("com.ws.study.prepost")
public class PrePostConfig { // initMethod和destroyMethod指定BeanWayService类的init和destroy方法在构造之后、Bean销毁之前执行
@Bean(initMethod = "init", destroyMethod = "destory")
BeanWayService beanWayService(){
return new BeanWayService();
} @Bean
JSR250WayService jsr250WayService(){
return new JSR250WayService();
}
}

5) 运行类

 package com.ws.study.prepost;

 import org.springframework.context.annotation.AnnotationConfigApplicationContext;

 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();
} }

6) 运行结果

 五月 31, 2018 10:33:21 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@dbe50f: startup date [Thu May 31 22:33:21 CST 2018]; root of context hierarchy
初始化构造函数-BeanWayService
@Bean-init-method
初始化构造函数-JSR250WayService
jsr250-init-method
五月 31, 2018 10:35:58 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@dbe50f: startup date [Thu May 31 22:33:21 CST 2018]; root of context hierarchy
jsr250-destroy-method
@Bean-destroy-method

4. Profile

Profile为在不同环境下使用不同的配置提供了支持(开发环境下的配置和生产环境下的配置肯定是不同的,如数据库配置)。

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

b. 通过设定jvm的srping.profiles.active参数来设置配置环境

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

示例:

1) 示例Bean

 package com.ws.study.profile;

 public class DemoBean {

 	private String content;

 	public DemoBean(String content){
super();
this.content = content;
} public String getContent() {
return content;
} public void setContent(String content) {
this.content = content;
} }

2) Profile配置

 package com.ws.study.profile;

 import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; @Configuration
public class ProfileConfig { @Bean
// Profile为dev时实例化devDemoBean
@Profile("dev")
public DemoBean devDemoBean(){
return new DemoBean("from devlopment profile");
} @Bean
// Profile为prod时实例化prodDemoBean
@Profile("prod")
public DemoBean proDemoBean(){
return new DemoBean("from production profile");
}
}

3) 运行类

 package com.ws.study.profile;

 import org.springframework.context.annotation.AnnotationConfigApplicationContext;

 public class Main {

 	public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
// 先将活动的Profile设置为prod
context.getEnvironment().setActiveProfiles("prod");
// 后置注册Bean配置类,不然会报Bean未定义的错误
context.register(ProfileConfig.class);
// 刷新容器
context.refresh(); DemoBean demoBean = context.getBean(DemoBean.class); System.out.println(demoBean.getContent()); context.close();
} }

4) 设置为prod的运行结果

 五月 31, 2018 11:04:32 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@dbe50f: startup date [Thu May 31 23:04:31 CST 2018]; root of context hierarchy
from production profile
五月 31, 2018 11:05:05 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@dbe50f: startup date [Thu May 31 23:04:31 CST 2018]; root of context hierarchy

5) 设置为dev的运行结果

 五月 31, 2018 11:06:21 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a71e93: startup date [Thu May 31 23:06:21 CST 2018]; root of context hierarchy
from devlopment profile
五月 31, 2018 11:06:22 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1a71e93: startup date [Thu May 31 23:06:21 CST 2018]; root of context hierarchy

5. 事件(Application Event)

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

Spring事件需要遵循的流程:

a. 自定义事件,继承ApplicationEvent

b. 定义事件监听器,实现ApplicationListener

c. 使用容器发布事件

示例:

1) 自定义事件

 package com.ws.study.event;

 import org.springframework.context.ApplicationEvent;

 public class DemoEvent extends ApplicationEvent{
private static final long serialVersionUID = -7872648566400668161L; 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.ws.study.event;

 import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; @Component
// 实现ApplicationListener接口,并指定监听的时间类型
public class DemoListener implements ApplicationListener<DemoEvent>{ // 使用onApplicationEvent方法对消息进行接受处理
public void onApplicationEvent(DemoEvent event) {
String msg = event.getMsg();
System.out.println("我(bean-demoListener)接受到了bean-demoEvent发布的消息: "+msg);
}
}

3) 事件发布类

 package com.ws.study.event;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component; @Component
public class DemoPublisher { // 注入ApplicationContext用来发布事件
@Autowired
ApplicationContext applicationContext; public void publish(String msg){
// 使用ApplicationContext的publishEvent方法来发布
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}

4) 配置类

 package com.ws.study.event;

 import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component; @Component
@ComponentScan("com.ws.study.event")
public class EventConfig {
}

5) 运行类

 package com.ws.study.event;

 import org.springframework.context.annotation.AnnotationConfigApplicationContext;

 public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);
demoPublisher.publish("hello application envent");
context.close();
}
}

6) 运行结果

 五月 31, 2018 11:23:18 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@dbe50f: startup date [Thu May 31 23:23:18 CST 2018]; root of context hierarchy
我(bean-demoListener)接受到了bean-demoEvent发布的消息: hello application envent
五月 31, 2018 11:25:15 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@dbe50f: startup date [Thu May 31 23:23:18 CST 2018]; root of context hierarchy