且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

记录:使用IDEA编辑Spring配置文件profile属性时产生的命名重复问题

更新时间:2022-04-25 23:53:59

 该问题仅仅与IDE相关,不影响应用的正常运行。在Spring Tool Suite中不存在该问题,而IDEA中会体现出来。

 

  在使用IDEA创建了一个Spring的配置文件,其中指定了profile属性,在不同的profile下有同名Bean其报命名重复(下图红色部分)。

  

 记录:使用IDEA编辑Spring配置文件profile属性时产生的命名重复问题


  使用程序测试,发现是正常了,于是判断是IDEA做了一些手脚。


  这个问题产生的原因是该Spring的配置是自己直接从外部Copy或者创建一个xml文件编辑的,并没有添加了项目模块的Spring Application Context设置中去,因此IDEA给出了命名冲突的提示,这里猜测其只是单纯的判断Id的唯一性,如果通过beans.xsd去做校验应该是没有问题的。下面解决的办法是设置模型的相关信息。


记录:使用IDEA编辑Spring配置文件profile属性时产生的命名重复问题


编辑模块spring-boot-demo的Application Context,将spring-context.xml文件添加到 Spring Application Context中去。 这时候查看spring-context.xml文件是IDEA才认可该配置是Spring的配置,同提示选择profile。


记录:使用IDEA编辑Spring配置文件profile属性时产生的命名重复问题


 选择profile dev之后,IDEA友好的将非活动的profile以灰色呈现,不过具体应用中仍然需要指定活动的profile 如下代码片段所示.


1
2
3
4
5
6
System.setProperty("spring.profiles.active""product");
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
List<String> list = (List<String>) ctx.getBean("a");
for (String v : list) {
    System.out.println(v);
}


  另外更加beans-xsd定义在Beans节点下嵌套Beans需要放置在文档最后。定义如下:

  记录:使用IDEA编辑Spring配置文件profile属性时产生的命名重复问题


  这是强迫症吗?!。

  IDEA与Spring高度集成,其Spring Application Context的配置文件进行管理也是情理之中,并且有其价值所在,比如在单独测试某一个ApplicationContext,或者某一模块。



本文转自 secondriver 51CTO博客,原文链接:http://blog.51cto.com/aiilive/1661831,如需转载请自行联系原作者