Java Spring中xml配置优先于注释配置的示例

Java Spring中xml配置优先于注释配置的示例,java,spring,spring-mvc,annotations,xml-configuration,Java,Spring,Spring Mvc,Annotations,Xml Configuration,在我读过的一本书中,XML配置比注释配置具有更高的优先级 但这方面没有任何例子 你能举个例子吗?这里有一个简单的例子,展示了基于xml的Spring配置和基于Java的Spring配置的混合。示例中有5个文件: Main.java AppConfig.java applicationContext.xml HelloWorld.java HelloUniverse.java 首先尝试使用applicationContext文件中注释掉的helloBeanbean运行它,您会注意到helloBe

在我读过的一本书中,XML配置比注释配置具有更高的优先级

但这方面没有任何例子


你能举个例子吗?

这里有一个简单的例子,展示了基于xml的Spring配置和基于Java的Spring配置的混合。示例中有5个文件:

Main.java
AppConfig.java
applicationContext.xml
HelloWorld.java
HelloUniverse.java
首先尝试使用applicationContext文件中注释掉的
helloBean
bean运行它,您会注意到
helloBean
bean是从AppConfig配置类实例化的。然后使用applicationContext.xml文件中未注释的
helloBean
bean运行它,您会注意到xml定义的bean优先于AppConfig类中定义的bean


Main.java

package my.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

   public static void main(String[] args) {
      ApplicationContext ctx = new AnnotationConfigApplicationContext( AppConfig.class );
      ctx.getBean("helloBean"); 
   }
}

AppConfig.java

package my.test;
import org.springframework.context.annotation.*;

@ImportResource({"my/test/applicationContext.xml"})
public class AppConfig {

   @Bean(name="helloBean")
   public Object hello() {
      return new HelloWorld();
   }
}

ApplicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="helloBean" class="my.test.HelloUniverse"/>

</beans>

HelloWorld.java

package my.test;

public class HelloWorld {

   public HelloWorld() {
      System.out.println("Hello World!!!");
   }
}

当我们更喜欢XML文件的集中式、声明式配置时,使用基于XML的配置。当许多配置发生变化时。它让您清楚地了解这些配置是如何连接的。基于XML的解耦比基于注释的松散得多。

查看这篇文章,我认为一切都在那里@Tom可能会有更好的答案:-)。还没有结束呢。@Tom没关系。祝你好运
package my.test;

public class HelloWorld {

   public HelloWorld() {
      System.out.println("Hello World!!!");
   }
}