Spring 实战-第三章-环境与Profile

对于不同的环境,需要使用不同的配置,但是不能因为每次切换环境,就要修改代码,所以需要根据环境自动的使用配置。

在Spring中通过@Profile注解,来实现配置的自动切换。

1.声明接口

package main.java.soundsystem;
public interface CompactDisc {
    void play();
}

2.开发环境实现,通过@Profile("dev”)标签,表明这是一个在dev环境中使用的实现

package main.java.soundsystem;

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

@Component
@Profile("dev")
public class SgtPepper implements CompactDisc {
    private String title ="Sgt. Pepper's Lonely Hearts Club Band";
    private String artist="The Beatles";
    @Override
    public void play() {
        System.out.println("Playing "+ title +" by "+artist);
    }
}

3.测试环境实现,通过@Profile("test”)标签,表明这是一个在test环境中使用的实现

package main.java.soundsystem;

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

@Component
@Profile("test")
public class YellowSubmarine implements CompactDisc{
    private String title ="Yellow Submarine";
    private String artist="The Beatles";
    @Override
    public void play() {
        System.out.println("Playing "+ title +" by "+artist);
    }{
    }
}

3.编写配置

package main.java.soundsystem;
import org.springframework.context.annotation.*;

@Configuration
@ComponentScan
public class CDPlayerConfig {

}

这里使用的是自动发现的方式,直接在前面的实现中增加@Profile注解,来表示其使用环境,当时用JavaConfig的时候,要在配置类中设置环境

package main.java.soundsystem;
import org.springframework.context.annotation.*;

@Configuration
//@ComponentScan
public class CDPlayerConfig {

    @Bean
    @Profile("dev")
    public CompactDisc sgtPeppers() {
        return new SgtPepper();
    }

    @Bean
    @Profile("test")
    public CompactDisc yellowSubmarine(){
        return new YellowSubmarine();
    }

}

4.激活profile,使用@ActiveProfile注解

package main.java.soundsystem;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {CDPlayerConfig.class})
@ActiveProfiles("test")
public class CDPlayerTest {
    @Autowired
    private CompactDisc cd;

    @Test
    public void cdShouldNotBeNull() {
        assertNotNull(cd);
        cd.play();
    }

}

有两个属性控制profile的使用:1.spring.profiles.active,2.spring.profiles.default

有多种方式来设置这两个属性

  • 作为DispatcherServlet的初始化参数;
  • 作为Web应用的上下文参数;
  • 作为JNDI条目;
  • 作为环境变量;
  • 作为JVM的系统属性
  • 在集成测试类上,使用@ActiveProfiles注解设置
原文地址:https://www.cnblogs.com/lvjianwei/p/7463813.html