spring boot 환경 나누기(profiles)

2016. 7. 18. 10:38OpenSource/Spring Boot

반응형



TEST Code


@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = LineupFantaApplication.class)

public class ServerHolderTest {


    public static final Logger logger = LoggerFactory.getLogger(ServerHolderTest.class);



    @Autowired ServerHolder serverHolder;


//    @Before

//    public void setUp(){}


    @Test

    public void testServerProfiles() throws Exception {

        Map<String,Map<String,String>> servers = serverHolder.getServerInfo();

        Assert.assertThat(servers.size(), is(1));

    }


} 


옛날 spring 방식하고 다르게 C언어처럼 main이 있으니 @SpringApplicationConfiguration(classes = LineupFantaApplication.class) 만 추가해주면 컨텍스트 쭉쭉 올라감! 굿굿!


@Autowired된 친구쪽에서 application.yml 읽어들임!

application.yml은 우리가 사용하게 되는 application.properties와 같은 친구!




@Component

@ConfigurationProperties(locations={"classpath:application.yml"})

public class ServerHolder {


    public Map<String, Map<String, String>> serverInfo = new HashMap<String, Map<String, String>>();

    public Map<String, Map<String, String>> getServerInfo() {

        return serverInfo;

    }

} 


application.yml의 내용은 아래와 같음.

serverInfo:

    - name: lineup

      ip: xxx.xxx.xxx.xxx

---


spring:

    profiles: real

serverInfo:

    - name: lineup

      ip: xxx.xxx.xxx.xxx



사용법은 아래와 같이 원하는 곳에서 사용하면 됨!

protected List<String> getBootstrapHosts() {

        return Arrays.asList(serverHolder.getServerInfo().get("0").get("ip"));

}



profiles는 tomcat같은 경우 vm argument에 이처럼 정보를 넣어서 사용!

-Dspring.profiles.active=real 옵션~안해주면 default 정보

1) 디폴트 : No active profile set, falling back to default profiles: default

2) -Dspring.profiles.active=real 옵션 : The following profiles are active: real


즉, 위의 옵션으로 yml의 정보를 real이냐 default냐 읽어들여서 profiles를할 수가 있다.

참고 사이트 : http://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html




반응형