springboot中spring.profiles.active來引入多個properties文件 & Springboot獲取容器中對象


1.    引入多個properties文件

  很多時候,我們項目在開發環境和生成環境的環境配置是不一樣的,例如,數據庫配置,在開發的時候,我們一般用測試數據庫,而在生產環境的時候,我們是用正式的數據,這時候,我們可以利用profile在不同的環境下配置用不同的配置文件或者不同的配置

  spring boot允許你通過命名約定按照一定的格式(application-{profile}.properties)來定義多個配置文件,然后通過在application.properyies通過spring.profiles.active來具體激活一個或者多個配置文件,如果沒有沒有指定任何profile的配置文件的話,spring boot默認會啟動application-default.properties。

  profile的配置文件可以按照application.properties的放置位置一樣,放於以下四個位置,

當前目錄的 “/config”的子目錄下
當前目錄下
classpath根目錄的“/config”包下
classpath的根目錄下

 

常見的應用場景

1.    多環境切換

在Spring Boot中多環境配置文件名需要滿足application-{profile}.properties的格式,其中{profile}對應你的環境標識,比如:
  application-dev.properties:開發環境
  application-test.properties:測試環境
  application-prod.properties:生產環境

我們在總的applications.properties文件中可以通過下面切換:

spring.profiles.active=dev

 

2.    我們進行分模塊開發的時候如下:

  在dao層的模塊中有下面配置:    application-dao.properties

內容如下:

############################################################
#
# Mybatis settings
#
############################################################
#jiazai mybatis peizhiwenjian(**代表任意目錄,*代表任意多個字符)
mybatis.mapper-locations = classpath:mapper/**/*Mapper.xml
mybatis.config-location = classpath:mybatis/SqlMapConfig.xml
mybatis.type-aliases-package = cn.qlq.bean

############################################################
#
# datasource settings
#
############################################################
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456

 

我們在總的applications.properties文件可以通過下面方式引入上面properties文件:

spring.profiles.active=dao

 

補充:代碼也可以根據當前激活的環境來進行IOC生成對應的bean,如下:

(1)application.properties激活dev對象

spring.profiles.active=dev

(2)代碼中根據激活的環境生成對象:

package com.zd.bx.service;

public interface TestService {

    void test1();
}

dev環境的實現類:

package com.zd.bx.service;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Service
@Profile("dev")
public class DevTestService implements TestService {

    @Override
    public void test1() {
        System.out.println("test1 dev");
    }
}

prod環境的實現類:

package com.zd.bx.service;

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

@Service
@Profile("prod")
public class ProdTestService implements TestService {

    @Override
    public void test1() {
        System.out.println("test1 prod");
    }

}

  Profile注解可以接受一個數組,多個激活的環境。源碼如下:

/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. */
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();

}

 

補充:application.properties也可以引入多個properties文件,如下

# include激活多個包
#spring.profiles.include=dev

 

2.獲取容器中對象

  直接像在spring中獲取會NPE異常。需要改裝成下面工具類:

package cn.qs.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringBootUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBootUtils.applicationContext = applicationContext;
    }

    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    public static <T> T getBean(String beanName, Class<T> beanClass) {
        return applicationContext.getBean(beanName, beanClass);
    }
}

進一步封裝成如下工具類:

package cn.qs.utils;import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;public class SystemUtils {
    private SystemUtils() {
    }
public static <T> T getContextBean(Class<T> clazz) {
        WebApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext();
         T bean = currentWebApplicationContext.getBean(clazz);// 根據類型獲取對象

        return bean;
    }
}

 

 

使用方法:

UserHealthService userHealthService = SpringBootUtils.getBean(UserHealthService.class);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM