配置類
package com.ysy.config;
import com.ysy.bean.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Profile("testB")
@Configuration
public class MainConfigOfProfile {
@Profile("testA")
@Bean
public DataSource dataSourceA(){
DataSource dataSource = new DataSource();
dataSource.setUser("A");
dataSource.setPasswd("1");
return dataSource;
}
@Profile("devB")
@Bean
public DataSource dataSourceB(){
DataSource dataSource = new DataSource();
dataSource.setUser("A");
dataSource.setPasswd("1");
return dataSource;
}
@Profile("proC")
@Bean
public DataSource dataSourceC(){
DataSource dataSource = new DataSource();
dataSource.setUser("A");
dataSource.setPasswd("1");
return dataSource;
}
}
測試類
package com.ysy.test;
import com.ysy.config.MainConfigOfProfile;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class IOCTestOfProfile {
@Test
public void test01(){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("testA");
context.register(MainConfigOfProfile.class);
context.refresh();
print(context);
}
private void print(AnnotationConfigApplicationContext context) {
String[] beanDefinitionNames = context.getBeanDefinitionNames();
for (String name:beanDefinitionNames){
System.out.println(name);
}
}
}