package com.xueyou.demo;
public interface MoveFactor {
void speak();
}
Person.java
package com.xueyou.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Person {
@Autowired
private MoveFactor moveFactor;
public void speak(){
moveFactor.speak();
}
}
Chinese.java
package com.xueyou.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Configuration
@Profile(value = "dev")
@Component
public class Chinese implements MoveFactor {
@Override
public void speak() {
System.out.println("我是中国人");
}
}
English.java
package com.xueyou.demo;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("qa")
public class English implements MoveFactor{
@Override
public void speak() {
System.out.println("i am an English");
}
}
German.java
package com.xueyou.demo;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("prod")
public class German implements MoveFactor{
@Override
public void speak() {
System.out.println("i am a German");
}
}
使用springtest进行测试
package com.xueyou.demo;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = App.class)
@ActiveProfiles("dev")
public class SpringTest {
@Autowired
Person p;
@Test
public void testProfile(){
p.speak();
}
}
运行结果:
当修改@ActiveProfile中的值时,输出的内容也会随之改变。
如果使用的是main函数进行真正的开发、测试和上线时,我们需要设置一下运行参数:
-D 后面加上需要设置的spring的属性,就能够在main函数中使用了。
App.java
package com.xueyou.demo;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Hello world!
// */
@Configuration
@ComponentScan(basePackages = {"com.xueyou.demo"})
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(com.xueyou.demo.App.class);
Person p = context.getBean(Person.class);
p.speak();
}
}