簡介
這個注解很簡單,就是導入spring的xml配置文件
直接來看spring官方文檔:
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.
當我們使用java配置類的時候,比如springboot工程,就推薦使用java配置類,理論上我們可以完全消除xml配置文件,但是有時候我們需要導入spring的xml配置文件,就需要使用這個注解
舉例:
首先是我們的java配置類
@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource() {
return new DriverManagerDataSource(url, username, password);
}
}
properties-config.xml
<beans>
<context:property-placeholder location="classpath:/com/acme/jdbc.properties"/>
</beans>
jdbc.properties
jdbc.properties
jdbc.url=jdbc:hsqldb:hsql://localhost/xdb
jdbc.username=sa
jdbc.password=
運行測試方法:
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
TransferService transferService = ctx.getBean(TransferService.class);
// ...結果略
}
說明
以上是spring官方文檔對於該注解的說明和示例,比較簡單,不贅述。