Reputation: 37034
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?
Upvotes: 9
Views: 6075
Reputation: 1
XML based configurations are used when we prefer centralized, declarative configurations of XML files. And when many of the configurations change. It gives you a clear idea how these configurations are wired. XML based is more loosely decoupled than annotation based.
Upvotes: -1
Reputation: 3166
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!!!");
}
}
Upvotes: 11