簡體   English   中英

Spring默認配置有Profile

[英]Spring default wiring with Profile

我有兩個豆子。 兩者都實現了郵件功能。 一個僅在部署到應用程序服務器時才起作用。 另一個用於測試。

我們為每個開發人員和環境提供配置文件 我想在實際測試時才連接測試bean。 不測試時應該使用另一個bean。 我該如何存檔?

@Component
@Profile("localtest")
public class OfflineMail implements Mailing {}

解決方法:

使用“默認”我在某處讀到了這個內容,但對於像“dev”這樣的配置文件似乎沒有回退到“默認”:

@Component
@Profile("default")
public class OnlineMail implements Mailing {}

- >沒有找到布線的bean的例外情況。

離開個人資料:

@Component
public class OnlineMail implements Mailing {}

- >運行“localtest”配置文件時引發一個唯一的異常。

添加所有檔案:

@Component
@Profile("prod")
@Profile("integration")
@Profile("test")
@Profile("dev1")
@Profile("dev2")
@Profile("dev3")
...
public class OnlineMail implements Mailing {}

這實際上是有效的,但是我們的開發人員沒有編號,他們使用“dev <WindowsLogin>”並添加配置文件,可能適用於一個bean,但是當一個bean使用它時會遇到麻煩,因為這肯定會變得很難看。

使用類似@Profile(“!localtest”)的東西似乎也不行。

有沒有人知道更好的方法來獲得“如果沒有找到特定的bean,默認連線”?

我終於找到了一個簡單的方法。

默認情況下,在線郵件剛剛連線。

@Component
public class OnlineMail implements Mailing {}

使用@Primary注釋,脫機郵件優先於OnlineMail,並避免使用Unique異常。

@Component
@Profile("localtest")
@Primary
public class OfflineMail implements Mailing {}

嘗試這個:

@Component
@Profile("production")
public class OnlineMail implements Mailing {}

@Component
@Profile("localtest")
public class OfflineMail implements Mailing {}

然后使用@ActiveProfiles(“localtest”)運行測試,並使用“production”作為DEFAULT配置文件運行生產環境。

另外我希望在下一版本的Spring ActiveProfilesResolver中引入SPR-10338 - 它可能對你有所幫助(避免“dev1”,“dev2”等)。

Spring支持很好地通過@Profile注入Bean:

interface Talkative {
    String talk();
}

@Component
@Profile("dev")
class Cat implements Talkative {
        public String talk() {
        return "Meow.";
    }
}

@Component
@Profile("prod")
class Dog implements Talkative {
    public String talk() {
        return "Woof!";
    }
}

適用於單元測試

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContex-test.xml"})
@ActiveProfiles(value = "dev")
public class InjectByDevProfileTest
{
    @Autowired
    Talkative talkative;

    @Test
    public void TestTalkative() {
        String result = talkative.talk();
        Assert.assertEquals("Meow.", result);

    }
}

在Main()中工作:

@Component公共類Main {

        public static void main(String[] args) {
            // Enable a "dev" profile
            System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
            ApplicationContext context =
                    new ClassPathXmlApplicationContext("applicationContext.xml");
            Main p = context.getBean(Main.class);
            p.start(args);
        }

        @Autowired
        private Talkative talkative;

        private void start(String[] args) {
            System.out.println(talkative.talk());
        }
    }

檢查這個演示代碼: https//github.com/m2land/InjectByProfile

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM