天天看點

spring源碼附錄(2)spring profile屬性的簡單使用

一、profile能幹嘛

比如:在開發時進行一些資料庫測試,希望連結到一個測試的資料庫,以避免對開發資料庫的影響。

比如:一部分bean希望在環境一種實用,一部分bean希望在環境二中使用

二、demo

需求:一部bean屬于生産環境,一部分bean屬于開發環境

目錄結構:

spring源碼附錄(2)spring profile屬性的簡單使用

IHelloService:

package com.profile.service;

public interface IHelloService {

    void sayHello();
}
           

ProduceHelloServiceImpl:

package com.profile.service.impl.pro;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.profile.service.IHelloService;

@Component
public class ProduceHelloServiceImpl implements IHelloService{

    public void sayHello() {
        System.out.println("hi,this is produce environment.");
    }

}
           

DevHelloServiceImpl:

package com.profile.service.impl.dev;

import org.springframework.stereotype.Component;

import com.profile.service.IHelloService;

@Component
public class DevHelloServiceImpl implements IHelloService{

    public void sayHello() {
        System.out.println("hi,this is development environment.");
    }

}
           

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd"> 

<beans profile="development"> 
    <context:component-scan base-package="com.profile.service.impl.dev" /> 
</beans> 

<beans profile="produce"> 
    <context:component-scan base-package="com.profile.service.impl.pro" /> 
</beans> 

</beans>
           

TestProfiles:

package com.profile.app;

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;

import com.profile.service.IHelloService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
@ActiveProfiles("produce")
public class TestProfiles {

    @Autowired
    private IHelloService hs;

    @Test 
    public void testProfile() throws Exception { 
        hs.sayHello(); 
    }

}
           

輸出:

spring源碼附錄(2)spring profile屬性的簡單使用

繼續閱讀