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 ...
随机推荐
- Leetcode_35_Search Insert Position
本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43739647 Given a sorted array a ...
- Adobe Audition 基本使用
1.1简介 Adobe Audition (前身是Cool Edit Pro) 是Adobe公司开发的一款功能强大.效果出色的多轨录音和音频处理软件.它是一个非常出色的数字音乐编辑器和MP3制作软件. ...
- Java-ServletContextEvent-ServletContextAttributeEvent
//这是一个事件类用来通知一个web 应用的servlet 上下文的改变 public class ServletContextEvent extends java.util.EventObject ...
- 打开Visual Studio 2010,左下角显示正在从包...加载工具箱内容,卡住5、6秒!!!
在VS2010命令提示符用 devenv /ResetSkipPkgs 或者 devenv /ResetSettings
- RedHat系列软件管理(第二版) --脚本安装
RedHat系列软件管理 --脚本安装 一.解压缩 tar -zxvf webmin-1.700.tar.gz 二.进入相关目录 cd webmin-1.700 三.如果此时执行./configure ...
- how tomcat works 读书笔记 八 载入器下
载入类 我们看看之前的文章,这一节就从SimpleWrapper的loadServlet讲起. SimpleWrapper.java如下(省略了try catch及其他部分代码) public Ser ...
- PS 图像调整算法——自动对比度 (Auto Contrast)
PS 给出的定义: Enhance Monochromatic Contrast: Clips all channels identically. This preserves the overall ...
- XMPP系列(一):OpenFire环境搭建
XMPP的服务器可以用OpenFire.ejabberd.jabberd2.x.Prosody.Tigase,其中比较常用的是OpenFire和ejabberd,还可以自己写服务器,我们公司的服务器端 ...
- Android切换前后置摄像头并录制视频
项目需要对微信的视频模块也看了一下,在此就对这块进行了一个开发.首先给出效果图 首先给出java代码 /** * RecordActivity.java * 版权所有(C) 2013 * 创建:cui ...
- LeetCode之旅(19)-Power of Two
题目 Given an integer, write a function to determine if it is a power of two. Credits: Special thanks ...