Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of xml config taking precedence over annotation config in Spring

In a book I have read, that XML configuration has higher priority than annotation configuration.

But there aren't any examples of it.

Could you show an example of it?

like image 302
gstackoverflow Avatar asked Feb 17 '14 10:02

gstackoverflow


1 Answers

Here's a simple example showing a mix of xml based Spring config and Java based Spring config. There are 5 files in the example:

Main.java
AppConfig.java
applicationContext.xml
HelloWorld.java
HelloUniverse.java

Try running it first with the helloBean bean commented out in the applicationContext file and you will notice that the helloBean bean is instantiated from the AppConfig configuration class. Then run it with the helloBean bean uncommented in the applicationContext.xml file and you will notice that the xml defined bean takes precedence over the bean defined in the AppConfig class.


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>


HelloUniverse.java

package my.test;

public class HelloUniverse {

   public HelloUniverse() {
      System.out.println("Hello Universe!!!");
   }
}


HelloWorld.java

package my.test;

public class HelloWorld {

   public HelloWorld() {
      System.out.println("Hello World!!!");
   }
}
like image 98
Tom Avatar answered Sep 22 '22 03:09

Tom