2014-02-17 95 views
9

在我读过的书中,XML配置的优先级高于注释配置。xml配置优先于Spring中注解配置的示例

但没有任何它的例子。

您能举一个例子吗?

+0

检查这个帖子,我认为一切都在那里http://stackoverflow.com/questions/15233766/what-is-the-precedence-of-spring-beans-definitions –

回答

10

下面是一个简单的例子,展示了基于xml的Spring配置和基于Java的Spring配置的组合。有5个文件中的示例:

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

尝试使用helloBean豆ApplicationContext中的文件注释掉首先运行它,你会发现,helloBean豆是从了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> 


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!!!"); 
    } 
} 
+0

谢谢 - 这是真的工程 – gstackoverflow

+0

@Tom可能还有更好的答案:-)。它还没有结束。 – Gangnus

+0

@Tom没关系。祝你好运! – Gangnus

-1

当我们宁愿集中,声明的XML文件配置的基于XML配置使用。当许多配置发生变化时。它给你一个清晰的概念如何连接这些配置。基于XML比基于注解更松散地解耦。