Spring注解(环境)
以数据库为例:
引入 c3p0数据源maven坐标
数据库驱动
@Configuration
@PropertySource("classpath:/db.config.properties")
public class ProfileConfig implements EmbeddedValueResolverAware {
//方法一
@Value("${db.user}")
private String user;
//方法三 通过值解析器
private StringValueResolver valueResolver;
private String driverClass;
@Profile("test")
@Bean(name="testDataSource") //方法二
public ComboPooledDataSource dataSourceTest(@Value("${db.password}") String pwd) throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setUser("root");
dataSource.setPassword(pwd);
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setDriverClass(driverClass);
return dataSource;
}
@Profile("dev")
@Bean(name="devDataSource") public ComboPooledDataSource dataSourceDev() throws Exception{ ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setUser(user); dataSource.setPassword("root"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/dev"); dataSource.setDriverClass(driverClass); return dataSource; } //重写方法 public void setEmbeddedValueResolver(StringValueResolver resolver) { this.valueResolver = resolver; driverClass = valueResolver.resolveStringValue("${db.driverClass}"); } }
这样就可以将数据源注册到容器中了
如何激活呢? 通过@Profile !
指定组件在哪个环境的情况下 才能被注册到容器中,不指定任何环境下都能注册。
只有当激活的bean 才能被注册进来
加了环境表示@Profile 的bean 只有当环境被激活的 才可以注册到容器 默认是default
激活方式:
使用参数方式激活
使用idea的界面激活
通过代码的方式激活:
public class test {
@Test
public void test01(){
//使用无参构造器 创建applicationContext (详情自己研究下有参构造器的方法)
AnnotationConfigApplicationContext applicationContext =new AnnotationConfigApplicationContext();
//设置需要激活的环境
applicationContext.getEnvironment().setActiveProfiles("dev","test"); //可以设置多个
//注册主配置类
applicationContext.register(Profile.class);
//启动刷新容器
applicationContext.refresh();
}
}
@Profile 还可以标注在类上: 写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能生效
没有标注@Profile的ben, 在任何环境下都是加载的
IOC小结: