Java Spring beans的profile属性切换环境

1585364631
2023-02-26 / 0 评论 / 126 阅读 / 正在检测是否收录...

Java Spring beans的profile属性切换环境

<beans>标签,除了经常用的作为根标签外,还可以嵌套在根标签内,使用profile属性切换开发环境

可以使用以下两种方式指定被激活的环境(dev为环境名):

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

beans.xml

    <bean class="org.example.UserDaoImpl" id="userDao"/>
    <bean class="org.example.UserServiceImpl" id="userService"/>
    <beans profile="dev">
        <bean id="userService1" class="org.example.UserServiceImpl"/>
    </beans>
    <beans profile="test">
        <bean id="userDao1" class="org.example.UserDaoImpl"/>
    </beans>

主函数调用

    public static void main(String[] args) {
        //    指定环境
        System.setProperty("spring.profiles.active","dev");

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        System.out.println(((UserService) applicationContext.getBean("userService")));
        System.out.println(((UserDao) applicationContext.getBean("userDao")));
        System.out.println(((UserService) applicationContext.getBean("userService1")));
        System.out.println(((UserDao) applicationContext.getBean("userDao1")));
    }

执行结果

org.example.UserServiceImpl@589b3632
org.example.UserDaoImpl@45f45fa1
org.example.UserServiceImpl@4c6e276e
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'userDao1' available
0

评论 (0)

取消