在我读过的一本书中,XML 配置比注释配置具有更高的优先级。
但是没有任何例子。
你能举个例子吗?
在我读过的一本书中,XML 配置比注释配置具有更高的优先级。
但是没有任何例子。
你能举个例子吗?
这是一个简单的示例,显示了基于 xml 的 Spring 配置和基于 Java 的 Spring 配置的混合。示例中有 5 个文件:
Main.java
AppConfig.java
applicationContext.xml
HelloWorld.java
HelloUniverse.java
尝试首先helloBean
在 applicationContext 文件中注释掉 bean 的情况下运行它,您会注意到helloBean
bean 是从 AppConfig 配置类实例化的。然后使用 applicationContext.xml 文件中未注释的 bean 运行它,helloBean
您会注意到 xml 定义的 bean 优先于 AppConfig 类中定义的 bean。
主.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();
}
}
应用程序上下文.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!!!");
}
}
当我们更喜欢 XML 文件的集中式、声明式配置时,使用基于 XML 的配置。当许多配置发生变化时。它让您清楚地了解这些配置是如何连接的。基于 XML 的解耦比基于注释的更松散。