随笔- 2079  评论- 223  文章- 4 

Spring框架中的@Import、@ImportResource注解

spring@Import

  • @Import注解在4.2之前只支持导入配置类
  • 在4.2,@Import注解支持导入普通的java类,并将其声明成一个bean

使用场景:

import注解主要用在基于java代码显式创建bean的过程中,用于将多个分散的java config配置类融合成一个更大的config类。其实除了 import注解外,还有 importResource注解,其作用都类似。配置类的组合主要发生在跨模块或跨包的配置类引用过程中。

 示例1:

一般来说, 需要按模块或类别 分割Spring XML bean文件 成多个小文件, 使事情更容易维护和模块化。 例如,
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <import resource="config/customer.xml"/>
    <import resource="config/scheduler.xml"/>
 
</beans>
Spring3 JavaConfig它等效于 @Import 功能
package com.yiibai.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ CustomerConfig.class, SchedulerConfig.class })
public class AppConfig {

}

 

在列表中,@Import 是被用来整合所有在@Configuration注解中定义的bean配置。这其实很像我们将多个XML配置文件导入到单个文件的情形。@Import注解实现了相同的功能。本文会介绍使用@Import注解来导入spring工程中的JavaConfig文件.

在下面的例子中,我创建了两个配置文件,然后导入到主配置文件中。最后使用主配置文件来创建context.

示例2:spring4.2之前导入配置类

//Car.java
package javabeat.net.basic;
public interface Car {
    public void print();
}

//Toyota.java

package javabeat.net.basic;
import org.springframework.stereotype.Component;
@Component
public class Toyota implements Car{
    public void print(){
        System.out.println("I am Toyota");
    }
}
//Volkswagen.java
package javabeat.net.basic;
import org.springframework.stereotype.Component;
@Component
public class Volkswagen implements Car{
    public void print(){
        System.out.println("I am Volkswagen");
    }
}
//JavaConfigA.java

package javabeat.net.basic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfigA {
    @Bean(name="volkswagen")
    public Car getVolkswagen(){
        return new Volkswagen();
    }
}

//JavaConfigB.java

package javabeat.net.basic;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JavaConfigB {
    @Bean(name="toyota")
    public Car getToyota(){
        return new Toyota();
    }
}

//ParentConfig.java

package javabeat.net.basic;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({JavaConfigA.class,JavaConfigB.class})
public class ParentConfig {
    //Any other bean definitions
}

//ContextLoader.java

package javabeat.net.basic;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ContextLoader {
    public static void main (String args[]){
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ParentConfig.class);
        Car car = (Toyota)context.getBean("toyota");
        car.print();
        car = (Volkswagen)context.getBean("volkswagen");
        car.print();
        context.close();
    }
}

程序执行输出
I am Toyata
I am Volkswagen

示例3:spring4.2之后导入普通java bean

package com.dxz.imports;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(DemoService.class) // 在spring 4.2之前是不不支持的
public class DemoConfig {

}

package com.dxz.imports;

public class DemoService {
    public void doSomething() {
        System.out.println("everything is all fine");
    }
}
package com.dxz.imports;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.dxz.imports");
        DemoService ds = context.getBean(DemoService.class);
        ds.doSomething();
    }
}

结果:

everything is all fine

总结

本文作者介绍了@Import注解的使用。这个注解帮助我们将多个配置文件(可能是按功能分,或是按业务分)导入到单个主配置中,以避免将所有配置写在一个配置中。

二、@ImportResource

相当于:

<import resource="applicationContext-democonfig2.xml" />

示例4:

学习如何使用@ImportResource 和 @Value 注解进行资源文件读取

例子:

先创建一个MyDriverManager类(模拟读取数据库配置信息)

package com.dxz.imports4;

public class MyDriverManager {

    public MyDriverManager(String url, String username, String password) {
        System.out.println("url : " + url);
        System.out.println("username : " + username);
        System.out.println("password : " + password);
    }
}

 创建StoreConfig

package com.dxz.imports4;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource("classpath:applicationContext-democonfig2.xml")
public class StoreConfig {

    @Value("${url}")
    private String url;

    @Value("${username}")
    private String username;

    @Value("${password}")
    private String password;

    @Bean
    public MyDriverManager myDriverManager() {
        return new MyDriverManager(url, username, password);
    }
}

XML配置(context:property-placeholder 指定资源文件的位置)applicationContext-democonfig2.xml

<?xml version="1.0" encoding="UTF-8"?>
<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-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:property-placeholder location="classpath:config4.properties" />

    <context:component-scan base-package="com.dxz.imports4">
    </context:component-scan>

</beans>

 

  创建资源文件config4.properties

url=127.0.0.1
username=root
password=123456

 单元测试:

package com.dxz.imports4;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UnitTest {

    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext-democonfig2.xml");
        MyDriverManager service = (MyDriverManager) context.getBean("myDriverManager");
        System.out.println(service.getClass().getName());

    }
}

结果:

 

 

posted on 2014-06-17 09:13  duanxz  阅读(...)  评论(...编辑  收藏