25、自动装配-@Profile根据环境注册bean

  • 指定组件在哪个环境的情况下才能被注册到容器中
  • 加了环境标识的,只有这个环境被激活才能注册到组件中
  • 默认是default环境
  • 写在类上,整个配置类的激活的时候才能生效
  • 没有标注环境标识的bean,在任何环境下都是加载的
package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.core.env.AbstractEnvironment;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Profiles; @Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile { /**
* 指定组件在哪个环境的情况下才能被注册到容器中
* The set of profiles for which the annotated component should be registered.
*/
String[] value(); }

25.1 实现

package com.hw.springannotation.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver; import javax.sql.DataSource;
import java.beans.PropertyVetoException; /**
* @Description Profile
* @Author hw
* @Date 2018/11/29 19:25
* @Version 1.0
*/
@Component
@PropertySource(value = {"classpath:/datasource.properties"})
public class MainConfigOfProfile implements EmbeddedValueResolverAware { @Value("${db.username}")
private String username; private String driveClassName; private StringValueResolver resolver; public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.resolver = resolver;
this.driveClassName = this.resolver.resolveStringValue("${db.driveClassName}");
} @Profile("default")
@Bean
public DataSource dataSourceTest(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setDriverClass(driveClassName);
return dataSource;
} @Profile("dev")
@Bean
public DataSource dataSourceDev(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mysql");
dataSource.setDriverClass(driveClassName);
return dataSource;
} @Profile("prod")
@Bean
public DataSource dataSourceProd(@Value("${db.password}") String password) throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/qm_dmp");
dataSource.setDriverClass(driveClassName);
return dataSource;
}
}

运行:

25.2 切换环境-使用命令行动态参数

  • 在运行时指定
-Dspring.profiles.active=prod

25.3 切换环境-使用代码的方式

  • 之前使用的是有参构造器,配置加载完,容器就刷新了,所以使用无参构造器
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}

步骤

  1. 构造IOC容器
  2. 设置需要激活的环境
  3. 注入配置类
  4. 启动刷新容器
@Test
public void test() {
// 1. 构造IOC容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
// 2. 设置需要激活的环境(可以同时激活多个)
applicationContext.getEnvironment().setActiveProfiles("test", "dev");
// 3. 注入配置类
applicationContext.register(MainConfigOfProfile.class);
// 4. 启动刷新容器
applicationContext.refresh(); String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
} }

25、自动装配-@Profile根据环境注册bean的更多相关文章

  1. 24、自动装配-@Profile环境搭建

    24.自动装配-@Profile环境搭建 Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能. 开发环境.测试环境.正式环境 数据源切换 24.1 添加 数据源和jdbc驱动 ...

  2. Spring注解开发系列Ⅴ --- 自动装配&Profile

    自动装配: spring利用依赖注入和DI完成对IOC容器中各个组件的依赖关系赋值.自动装配的优点有: 自动装配可以大大地减少属性和构造器参数的指派. 自动装配也可以在解析对象时更新配置. 自动装配的 ...

  3. SpringBoot自动装配原理之Configuration以及@Bean注解的使用

    Configuration以及Bean注解的使用 该知识点在Spring中应该学过,没有学过或者遗忘的的朋友需要预习或温习前置知识点.SpringBoot其实就是Spring的进一步简化,所以前置知识 ...

  4. Spring学习03(Bean的自动装配)

    6.Bean的自动装配 6.1 自动装配说明 自动装配是使用spring满足bean依赖的一种方法 spring会在应用上下文中为某个bean寻找其依赖的bean. Spring中bean的三种装配机 ...

  5. spring实战二之Bean的自动装配(非注解方式)

    Bean的自动装配 自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bea ...

  6. Spring(九):Spring配置Bean(二)自动装配的模式、Bean之间的关系

    XML配置里的Bean自动装配 Spring IOC容器可以自动装配Bean,需要做的仅仅是在<bean>的autowire属性里指定自动装配的模式,模式包含:byType,byName, ...

  7. spring bean autowire自动装配

    转自:http://blog.csdn.net/xiao_jun_0820/article/details/7233139 autowire="byName"会自动装配属性与Bea ...

  8. Spring学习笔记--自动装配Bean属性

    Spring提供了四种类型的自动装配策略: byName – 把与Bean的属性具有相同名字(或者ID)的其他Bean自动装配到Bean的对应属性中. byType – 把与Bean的属性具有相同类型 ...

  9. SpringXML方式配置bean的自动装配autowire

    Spring的自动装配,也就是定义bean的时候让spring自动帮你匹配到所需的bean,而不需要我们自己指定了. 例如: User实体类里面有一个属性role 1 2 3 4 5 6 7 publ ...

随机推荐

  1. ubuntu18和windows10双系统时间不同步问题(Ubuntu)

    1.安装并校准时间 sudo apt install ntpdate sudo ntpdate time.windows.com 2.写入硬件配置 sudo hwclock --localtime - ...

  2. SDOI2010_大陆争霸(邻接表存图)

    题目描述 在一个遥远的世界里有两个国家:位于大陆西端的杰森国和位于大陆东端的 克里斯国.两个国家的人民分别信仰两个对立的神:杰森国信仰象征黑暗和毁灭 的神曾·布拉泽,而克里斯国信仰象征光明和永恒的神斯 ...

  3. php类常量

    类常量类常量可以使用define定义,也可用const定义,但是在类的内部,只允许用const定义,类常量不能更新,也不能删除类常量通常是大写的,两个单词之间用下滑线连接,如MY_NATION类常量在 ...

  4. DRF图片路径问题的解决方法,网上爬取的图片放到ImageFiled自动带上域名

    由于博客园不支持markdown,推荐下面的url访问 原创url: https://blog.csdn.net/weixin_42495873/article/details/89440437 - ...

  5. 使用Duilib开发Windows软件(5)——使用VLC做视频播放

    需求:调用PC上的摄像头拍照. 实现思路:接入视频流,截屏获取照片. 早期的vlc安装包(Windows)是附带sdk包的,现在的安装后已经没有了,原因如下: VLC SDK下载连接:https:// ...

  6. CSS之cursor用法

    cursor: url('~ROOT/shared/assets/image/vn-text-cursor-31-49.png') 22 22, nw-resize; 另外还有一个 cursor: g ...

  7. (一)Activiti简介

    一.概念 Activiti项目是一项新的基于Apache许可的开源BPM平台,从基础开始构建,旨在提供支持新的BPMN 2.0标准,包括支持对象管理组(OMG),面对新技术的机遇,诸如互操作性和云架构 ...

  8. Java Web-Filter and listener

    Java Web-Filter and listener Filter:过滤器 概述 拦截请求,完成一些特殊的功能. 过滤器的作用: 一般用于完成通用的一些操作,例如登录验证(通过session来判断 ...

  9. datatables初始化用法

    var recordTable = $('#record_table').DataTable({ "fnInitComplete": function () { //表格初始化完成 ...

  10. K2 BPM_K2受邀出席QAD 2019年亚太区用户大会_全业务流程管理专家

    6月12-13日,K2受邀参加了以“云聚创新,智造未来”为主题的QAD 2019年亚太区用户大会.会议上K2同与会嘉宾们共商制造业数字化转型,就如何用流程赋能企业实现智能制造进行了精彩分享. 近期发布 ...