Profile的使用

编程

MainConfigOfProfile.class

/**

* Profile

* Spring为我们提供的可以根据当前环境动态的激活和切换一系列组件的功能

*

* 开发环境、测试环境、生产环境

*

* @Profile 指定组件在哪个环境下才能被注册到环境中,不指定,任何环境下都能注册

* 1. 加了环境标识的bean,只有这个环境被激活时才能注册到容器中,

* 2. 写在配置类上时,只有指定环境的时候,整个配置类里面的所有配置才能生效

* 3. 没有标注环境标识的bean在任何环境下都加载

*/

@Profile("test")

@Configuration

@PropertySource("classpath:dbconfig.properties")

public class MainConfigOfProfile implements EmbeddedValueResolverAware {

@Value("${db.user}")

private String user;

private StringValueResolver valueResolver;

private String driverClass;

@Bean

public Yellow yellow() {

return new Yellow();

}

@Profile("dev")

@Bean

public DataSource dataSourceDev(@Value("${db.password}") String password) throws Exception {

ComboPooledDataSource dataSource = new ComboPooledDataSource();

dataSource.setUser(user);

dataSource.setPassword(password);

dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev");

dataSource.setDriverClass(driverClass);

return dataSource;

}

@Profile("test")

@Bean

public DataSource dataSourceTest(@Value("${db.password}") String password) throws Exception {

ComboPooledDataSource dataSource = new ComboPooledDataSource();

dataSource.setUser(user);

dataSource.setPassword(password);

dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");

dataSource.setDriverClass(driverClass);

return dataSource;

}

@Profile("prod")

@Bean

public DataSource dataSourceProd(@Value("${db.password}") String password) throws Exception {

ComboPooledDataSource dataSource = new ComboPooledDataSource();

dataSource.setUser(user);

dataSource.setPassword(password);

dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/prod");

dataSource.setDriverClass(valueResolver.resolveStringValue("${db.driverClass}"));

return dataSource;

}

public void setEmbeddedValueResolver(StringValueResolver resolver) {

valueResolver = resolver;

driverClass = resolver.resolveStringValue("${db.driverClass}");

}

}

dbconfig.properties

db.user=root

db.password=123456

db.driverClass=com.mysql.jdbc.driver

Yellow.class

public class Yellow {

}

以上是 Profile的使用 的全部内容, 来源链接: utcz.com/z/516834.html

回到顶部