I am studying for the Spring Core certification and I have a doubt related to the @import and the @importresource annotations use.
So for example I have a configuration class named RootConfig.java , this one:
@Configuration
@Import({AppConfig.class,DbConfig.class})
@ImportResource("classpath:/config/security-config.xml")
@EnableTransactionManagement
public class RootConfig {
}
So I know that in this example the:
@Import({AppConfig.class,DbConfig.class})
are importing 2 others configuration classes (something like including these configurations into the main configuration represented by my RootConfig.java configuration class.
Ant I understand that the:
@ImportResource("classpath:/config/security-config.xml")
are importing an XML file.
So my doubt is: why exist 2 differents annotations that do a very similar task? Why don't use a single annotation to import both configurations classes and resources (such as xml files or property files?)
This is only a semantic differentiation or there are something else?
@Import
Indicates one or more @Configuration
classes to import. For import Java code-based configuration. eg
@Configuration @Import({ DataSourceConfig.class, TransactionConfig.class }) public class AppConfig { ... }
See more in Using the @Import
annotation .
@ImportResource
Indicates one or more resources containing bean definitions to import. For import XML-based configuration or other non- @Configuration
bean definition resources. eg
@Configuration @ImportResource({"classpath:spring-security.xml"}) public class SecurityConfig { ... }
See more in @Configuration
class-centric use of XML with @ImportResource
.
@ImportResource is meant to be used in java-centric configuration context. The docs say,
In applications where @Configuration classes are the primary mechanism for configuring the container, it will still likely be necessary to use at least some XML. In these scenarios, simply use @ImportResource and define only as much XML as is needed. Doing so achieves a "Java-centric" approach to configuring the container and keeps XML to a bare minimum.
One important aspect is that when using @ImportResource XML configuration you can override the java-centric configuration using the @Bean annotation. This means that you can override the configuration (by changing the configuration XML) without impacting the code. This semantic gives you one context where you can consider using @ImportResource , and its in my view a very valuable asset 'cause one of the most common critique of the java-centric configuration is that it requires code recompile.
The second context is providing the means to gradually move from the XML centric to a java-centric configuration.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.