5. 基于注解的Spring应用 - Spring 配置@Primary和@Profile

348 阅读1分钟
  • 扩展:@Primary 注解用于标注相同类型的 Bean 优先被使用权, @Primary 是 Spring3.0 引入的,与 @Component@Bean 一起使用,标注该 Bean 的优先级更高,则在通过类型获取 Bean 或通过 @Autowired 根据类型进行注入时,会选用优先级更高的
@Repository("userDao")
public class UserDaoImpl implements UserDao{}

@Repository("userDao2")
@Primary
public class UserDaoImpl2 implements UserDao{}

@Bean
public UserDao userDao01(){ return new UserDaoImpl();}

@Bean
@Primary
public UserDao userDao02(){ return new UserDaoImpl2();}
  • 扩展: @Profile 注解的作用同于 xml 配置时学习 profile 属性,是进行环境切换使用的
<beans profile ="test"/>

注解 @Profile 标注在类或方法上,标注当前产生的 Bean 从属于哪个环境,只有激活了当前环境,被标注的 Bean 才能被注册到 Spring 容器里,不指定环境的 Bean ,任何环境下都能注册到 Spring 容器里

@Repository("userDao")
@Profile("test")
public class UserDaoImpl implements UserDao{}

@Repository("userDao2")
public class UserDaoImpl2 implements UserDao{}

可以使用以下两种方式指定被激活的环境:

  1. 使用命令行动态参数,虚拟机参数位置加载 -Dspring.profiles.active =test
  2. 使用代码的方式设置环境变量System.setProperty("spring.profiles.active","test")