spring源码附录(2)spring profile属性的简单使用
程序员文章站
2022-06-13 19:04:12
...
一、profile能干嘛
比如:在开发时进行一些数据库测试,希望链接到一个测试的数据库,以避免对开发数据库的影响。
比如:一部分bean希望在环境一种实用,一部分bean希望在环境二中使用
二、demo
需求:一部bean属于生产环境,一部分bean属于开发环境
目录结构:
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();
}
}
输出: