Spring Boot实战笔记(三)-- Spring常用配置(Bean的初始化和销毁、Profile)
一、Bean的初始化和销毁
在我们的实际开发的时候,经常会遇到Bean在使用之前或之后做些必要的操作,Spring对Bean的生命周期操作提供了支持。在使用Java配置和注解配置下提供如下两种方式:
(1)Java配置的方式:使用 @Bean 的 initMethod 和 destroyMethod(相当于xml配置中的 init-method 和 destroy-method)。
(2)注解方式:利用JSR-250的 @PostContruct 和 @PreDestroy。
演示:
1.增加 JSR-250 支持。
<!-- JSR-250 支持 -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
2.使用 @Bean 形式的Bean。
package com.ecworking.bean;
public class BeanWayService {
public void init(){
System.out.println("@Bean-init-method");
}
public BeanWayService() {
super();
System.out.println("初始化构造函数-BeanWayService");
}
private void destroy(){
System.out.println("@Bean-destroy-method");
}
}
3.使用JSR250形式的Bean。
package com.ecworking.bean; 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");
} @PreDestroy // 在Bean销毁之前执行
private void destroy(){
System.out.println("@JSR250-destroy-method");
}
}
4.配置类。
package com.ecworking.bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan("com.ecworking.bean")
public class PrePostConfig { // initMethod 和 destroyMethod 指定BeanWayService类的 init 和 destroy 方法在构造之后、Bean销毁之前执行
@Bean(initMethod = "init", destroyMethod = "destroy")
BeanWayService beanWayService(){
return new BeanWayService();
} @Bean
JSR250WayService jsr250WayService(){
return new JSR250WayService();
} }
5.运行。
package com.ecworking.bean;
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();
}
}
运行结果:

二、Profile
Prifile为不同环境下提供不同不同配置提供了支持(开发环境和生产环境下的配置肯定是不同的,例如,数据库的配置)。
1.通过设定Environment的 ActiveProfile来设定当前context需要使用的配置环境。在开发环境中使用@Profile注解类或方法,达到在不同环境下选择实例化不同的Bean。
2.通过设定jvm的spring.profile.active参数来设置配置环境。
3.Web项目设置在Servlet的context parameter中。
Servlet2.5及以下:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>production</param-value>
</init-param>
</servlet>
Servlet3.0及以上
public class WebInit implement WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException{
container.setInitParameter("spring.profiles.default", "dev");
}
}
演示:
1.示例Bean。
package com.ecworking.profile;
public class DemoBean {
private String content;
public DemoBean(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
2.profile配置。
package com.ecworking.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") // profile为dev时实例化devDemoBean
public DemoBean devDemoBean(){
return new DemoBean("from dev profile");
} @Bean
@Profile("prod") // profile为prod时实例化prodDemoBean
public DemoBean prodDemoBean(){
return new DemoBean("from prod profile");
}
}
3.运行。
package com.ecworking.profile;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("prod"); //先将活动的Profile设置为prod。
context.register(ProfileConfig.class); //后注册Bean配置类,不然会报Bean未定义的错误。
context.refresh(); //刷新容器
DemoBean demoBean = context.getBean(DemoBean.class);
System.out.println(demoBean.getContent());
context.close();
}
}
运行结果:

将 context.getEnvironment().setActiveProfiles("prod") 改为 context.getEnvironment().setActiveProfiles("dev") 效果如下:

Spring Boot实战笔记(三)-- Spring常用配置(Bean的初始化和销毁、Profile)的更多相关文章
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- spring boot实战(第十三篇)自动配置原理分析
前言 spring Boot中引入了自动配置,让开发者利用起来更加的简便.快捷,本篇讲利用RabbitMQ的自动配置为例讲分析下Spring Boot中的自动配置原理. 在上一篇末尾讲述了Spring ...
- Spring Boot 系列(三)属性配置&自定义属性配置
在使用spring boot过程中,可以发现项目中只需要极少的配置就能完成相应的功能,这归功于spring boot中的模块化配置,在pom.xml中依赖的每个Starter都有默认配置,而这些默认配 ...
- Spring Boot实战系列(7)集成Consul配置中心
本篇主要介绍了 Spring Boot 如何与 Consul 进行集成,Consul 只是服务注册的一种实现,还有其它的例如 Zookeeper.Etcd 等,服务注册发现在微服务架构中扮演这一个重要 ...
- Spring Boot实战笔记(二)-- Spring常用配置(Scope、Spring EL和资源调用)
一.Bean的Scope Scope描述的是Spring容器如何新建Bean实例的.Spring的Scope有以下几种,通过@Scope注解来实现. (1)Singleton:一个Spring容器中只 ...
- Spring Boot实战笔记(一)-- Spring简介
一.Spring 概述 Spring框架是一个轻量级的企业级开发的一站式解决方案.所谓的解决方案就是可以基于Spring解决所有的Java EE开发的所有问题. Spring框架主要提供了Ioc(In ...
- JavaEE开发的颠覆者 Spring Boot实战--笔记
1.Spring boot的三种启动模式 Spring 的问题 Spring boot的特点,没有特别的地方 1.Spring 基础 PS:关于spring配置 PS: 现在都已经使用 java配置, ...
- spring boot 实战笔记(一)
spring 概述: Bean :每一个被 Spring 管理的 JAVA对象,都称之为 Bean.Spring提供一个IoC容器来初始化对象,负责创建Bean, 解决对象之间的依赖管理和对象的使用. ...
- Spring Boot 菜鸟教程 application.properties 常用配置
SPRING CONFIG (ConfigFileApplicationListener) spring.config.name 配置文件名称,默认为application spring.config ...
随机推荐
- BAT Android工程师面试流程解析+还原最真实最完整的一线公司面试题
尊重原创,转载请写明原文出处:http://blog.csdn.net/sk719887916/article/details/47040931 (skay) 求职和我们每个人息息相关,而求职也有门道 ...
- 《java入门第一季》之面向对象(抽象类到底多抽象)
/* 抽象类的概述: 动物不应该定义为具体的东西,而且动物中的吃,睡等也不应该是具体的. 我们把一个不是具体的功能称为抽象的功能,而一个类中如果有抽象的功能,该类必须被称为是抽象类. 抽象类的特点: ...
- myeclipse 彻底让烦人的各种验证消失 让你的开发速度飞快
大家都知道,myeclipse的验证很吭爹,不但保存的时候要难,BUILD的时候也要验.常常为了等它而浪费了大浪的时间!!真不知道设计人员当初是怎么加进这种功能的.真心不需要. 以前都是到window ...
- 网站开发进阶(二十五)js如何将html表格导出为excel文件
js如何将html表格导出为excel文件 赠人玫瑰,手留余香.若您感觉此篇博文对您有用,请花费2秒时间点个赞,您的鼓励是我不断前进的动力,共勉! jsp页面数据导出成excel的方法很 ...
- 【一天一道LeetCode】#19. Remove Nth Node From End of List
一天一道LeetCode系列 (一)题目 Given a linked list, remove the nth node from the end of list and return its he ...
- MDX的实例讲解(排名前15的小例子)
MDX语句的特点: 大小写不分.members等于Members;downloads等于Downloads 维度的统计量指定要选择准确.downloads等于[Downloads] []可以少,不能多 ...
- OPEN A PO ORDER OR SO ORDER
OPEN PO ORDER fnd_function.Execute(Function_Name => 'PO_POXPOEPO', Open_Flag => 'Y', Session_F ...
- Xcode中iOS模拟器程序中的plist路径
Xcode6.4里写了个简单的iOS程序在模拟器中跑. 其中用到了NSUserDefaults来保存属性文件plist,那么这个文件实际路径在哪里呢?在网上搜了一下,发现几种说法(*表示当前用户名): ...
- Linux文件与目录管理 - ls, cp, mv
[root@www ~]# ls [-aAdfFhilnrRSt] 目录名称 [root@www ~]# ls [--color={never,auto,always}] 目录名称 [root@www ...
- ZooKeeper 会话超时
1.会话概述 在ZooKeeper中,客户端和服务端建立连接后,会话随之建立,生成一个全局唯一的会话ID(Session ID).服务器和客户端之间维持的是一个长连接,在SESSION_TIMEOUT ...