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. Lucas定理的运用及组合数奇偶性的判断

    组合数奇偶性的判断 对于C(n,k),若n&k == k 则c(n,k)为奇数,否则为偶数. 最直观的方法就是计算一下,然后看它的奇偶性:但是这个时间以及数据范围上都不允许: 另外一种方法就是 ...

  2. Anaconda安装报错

    通用解决方案:先卸载,然后重新安装(注意安装路径全英文且不要有空格),勾选添加环境变量选项

  3. Windows计划任务无法写Log的问题

    参照:https://www.cnblogs.com/jonezzz/p/10364153.html 使用WIndows计划任务去执行Exe文件时无法写Log,而Exe双击执行就能写Log,这是由于计 ...

  4. 谷歌(Google)学术镜像,谷歌镜像

    谷歌(Google)学术镜像,谷歌镜像 2019-09-03 15:32:26 Hinton-wu 阅读数 6743 文章标签: 谷歌google学术镜像 更多 分类专栏: 其他   版权声明:本文为 ...

  5. 时间格式_java

    @Test public void testDate(){ Date date=new Date(); System.out.println(date); /*日期格式*/ DateFormat df ...

  6. WebSocket协议探究(序章)

    一 WebSocket协议基于HTTP和TCP协议 与往常一样,进入WebSocket协议学习之前,先进行WebSocket协议抓包,来一个第一印象. WebSocket能实现客户端和服务器间双向.基 ...

  7. XML-RPC-2RPC

    远程过程调用协议 RPC一般指远程过程调用协议 RPC(Remote Procedure Call)—远程过程调用,它是一种通过网络从远程计算机程序上请求服务,而不需要了解底层网络技术的协议.RPC协 ...

  8. 如何使 JavaScript 更高效?

    传统的 Web 页面不会包含很多脚本,至少不会太影响 Web 页面的性能.然而,Web 页面变得越来越像应用程序,脚本对其的影响也越来越大.随着越来越多的应用采用 Web 技术开发,脚本性能的提升就变 ...

  9. bond模式详解

    目录 bond模式详解 一.什么是bond? 二.为什么使用bond? 三.bond模式配置 1.配置linux bond 2.将bond绑定到ovs上面(可选) 四.bond模式 1.模式0 2.模 ...

  10. 《深入Linux内核架构》笔记 --- 第一章 简介和概述

    Linux将虚拟地址空间划分为两个部分,分别称为内核空间和用户空间 各个系统进程的用户空间是完全彼此分离的,而虚拟地址空间顶部的内核空间总是同样的,无论当前执行的是哪个进程. 尽管Intel处理器区分 ...