zoukankan      html  css  js  c++  java
  • Spring中的@ImportResource

    简介

    这个注解很简单,就是导入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官方文档对于该注解的说明和示例,比较简单,不赘述。

    你所看得到的天才不过是在你看不到的时候还在努力罢了!
  • 相关阅读:
    laravel 查询指定字段的值
    laravel 连表查询数据库
    jar包在控制台下运行
    jsp 中文乱码
    PHP垃圾回收深入理解
    php在foreach中使用引用赋值&可能遇到的问题
    接口和抽象类有什么区别
    关于php优化 你必须知道的一些事情
    yii 表单小部件
    yii 表单小部件的使用方式
  • 原文地址:https://www.cnblogs.com/heliusKing/p/11487503.html
Copyright © 2011-2022 走看看