Spring 简单案例(spring profile)_03

[align=center][b] 我使用的是spring4.x,这里也只讨论spring4的新特性。[/b][/align]
spring profile 我个人理解其实就是为了在不同情况下,使用不同的方案。个人情况,想怎么用就怎么用呗。
废话不多说直接上代码,首先是配置文件:

package com.expect.oa.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.expect.oa.*")
//@ComponentScan(basePackages={"com.expect.oa.DI.*","com.expect.oa.DI2.*"})//多个包可以这样写
public class SpringConfig {

}

然后创建几个类,这里逻辑有必要说几句,有两个类都能够构造出一个同一个类,这样spring会报错,但是我们这里用了profile,这时候要看激活了哪一种方案就会用哪一种方案去构造。我这语言表达能力真狗屎,这我知道 ,还是看代码吧:

package com.expect.oa.profile;
//这是一个类,分别可以被类A,类B构造出来。
public class ProEntity {

public ProEntity(String pro) {

System.out.println(pro);

}
}


下面是类A,用于构造上面类的类,这样说心真的好累,哈哈:

package com.expect.oa.profile;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile(value={"profileA"})//注意这里哦,这里生命了A方案哦
public class Profile_A {

@Bean
public ProEntity getProEntity (){
return new ProEntity("这是A方案");
}

}

下面是类B,也是用于构造上上个类的,心好累,上代码:

package com.expect.oa.profile;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile(value={"profileB"})//注意这里哦,这里声明了B方案哦
public class Profile_B {

@Bean
public ProEntity getProEntity (){
return new ProEntity("这是B方案");
}

}

好了,我们测试吧:

package com.expect.oa.test;

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.expect.oa.config.SpringConfig;
import com.expect.oa.profile.ProEntity;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
@ActiveProfiles(value={"profileB"})//注意这里哦,这里激活了B方案哦。当然你也可以激活A
public class TestProfile {

@Autowired
ProEntity pEntity;

@Test
public void testProfile (){

}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值