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. 【坑】Mybatis 多次逆向工程生成mapper文件

    在使用 mybatis 逆向工程的时候,多次逆向工程生成的文件,是不会产生覆盖的,而是追加: 假如,你第一次逆向,发生数据库的某个字段类型错了,修改以后再次逆向,那么得到的 mapper文件,将是 2 ...

  2. 数值类型与std::string的相互转换

    1.使用std::stringstream: //将in_value值转换成out_type类型 template<class out_type, class in_value> out_ ...

  3. Hystrix(下),使用公共降级类

    使用Hystrix熔断(下) 在一个分布式系统里,一个服务依赖多个服务,可能存在某个服务调用失败,         比如超时.异常等,如何能够保证在一个依赖出问题的情况下,不会导致整体服务失败,   ...

  4. WebSocket协议探究(序章)

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

  5. .netcore项目中使用log4net

    log4net配置文件 引入log4net包,创建一个config目录,专门用来放配置文件,添加log4net.config文件. 编写配置文件. <?xml version="1.0 ...

  6. ElasticSearch创建动态索引

    ElasticSearch创建动态索引 需求:某实例需要按照月份来维护,所以之前的“写死”索引的方式当然不行了.通过百度和看SpringDataElasticSearch官方文档,最后解决了这个问题. ...

  7. 2、JDK8中的HashMap实现原理及源码分析

    本篇提纲.png 本篇所述源码基于JDK1.8.0_121 在写上一篇线性表的文章的时候,笔者看的是Android源码中support24中的Java代码,当时发现这个ArrayList和Linked ...

  8. spring.factories配置文件的工厂模式

    在springboot的各个依赖包下,我们经常看到META-INF/spring.factories这个文件.spring.factories文件的内容基本上都是这样的格式: # Initialize ...

  9. js循环及for-in , for-of的区别

    循环 字符串遍历:可通过for-of遍历字符串 for-in:遍历对象自身可继承可枚举属性 Object.keys():返回对象自身可枚举属性的键组成的数组 Object.getOwnProperty ...

  10. cygwin_exception::open_stackdumpfile: Dumping stack trace to HttpServer.exe.stackdump错误

    本来,我在Windows下使用Cygwin编译运行c程序,在执行*.exe时报出如题错误,我在Linux环境下使用gcc编译运行,则正常. 所以,当你无法解决上述问题时,换系统吧!