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()); }
}

结果:

Spring框架中的@Import、@ImportResource注解的更多相关文章

  1. spring框架中的@Import注解

    spring框架中的@Import注解 Spring框架中的@Import注解 在之前的文章中,作者介绍了Spring JavaConfig. 这是除了使用传统的XML文件之外,spring带来的新的 ...

  2. Spring框架中的AOP技术----注解方式

    利用AOP技术注解的方式对功能进行增强 CustomerDao接口 package com.alphajuns.demo1; public interface CustomerDao { public ...

  3. Spring框架入门之基于Java注解配置bean

    Spring框架入门之基于Java注解配置bean 一.Spring bean配置常用的注解 常用的有四个注解 Controller: 用于控制器的注解 Service : 用于service的注解 ...

  4. spring框架学习(五)注解

    注解Annotation,是一种类似注释的机制,在代码中添加注解可以在之后某时间使用这些信息.跟注释不同的是,注释是给我们看的,Java虚拟机不会编译,注解也是不编译的,但是我们可以通过反射机制去读取 ...

  5. Spring框架中 配置c3p0连接池 完成对数据库的访问

    开发准备: 1.导入jar包: ioc基本jar jdbcTemplate基本jar c3p0基本jar 别忘了mysql数据库驱动jar 原始程序代码:不使用配置文件方式(IOC)生成访问数据库对象 ...

  6. Spring框架中ModelAndView、Model、ModelMap区别

    原文地址:http://www.cnblogs.com/google4y/p/3421017.html SPRING框架中ModelAndView.Model.ModelMap区别   注意:如果方法 ...

  7. Spring框架中的定时器 使用和配置

    Spring框架中的定时器 如何使用和配置 转载自:<Spring框架中的定时器 如何使用和配置>https://www.cnblogs.com/longqingyang/p/554543 ...

  8. 细说shiro之五:在spring框架中集成shiro

    官网:https://shiro.apache.org/ 1. 下载在Maven项目中的依赖配置如下: <!-- shiro配置 --> <dependency> <gr ...

  9. Spring5源码解析-Spring框架中的单例和原型bean

    Spring5源码解析-Spring框架中的单例和原型bean 最近一直有问我单例和原型bean的一些原理性问题,这里就开一篇来说说的 通过Spring中的依赖注入极大方便了我们的开发.在xml通过& ...

随机推荐

  1. 现在有一张半径为r的圆桌,其中心位于(x,y),现在他想把圆桌的中心移到(x1,y1)。每次移动一步,都必须在圆桌边缘固定一个点然后将圆桌绕这个点旋转。问最少需要移动几步。

    // ConsoleApplication5.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<vector> ...

  2. SkipList跳跃表(Java实现)

    取自网络https://github.com/spratt/SkipList AbstractSortedSet.java package skiplist_m; /***************** ...

  3. 多媒体开发之---live555 分析客户端

    live555的客服端流程:建立任务计划对象--建立环境对象--处理用户输入的参数(RTSP地址)--创建RTSPClient实例--发出DESCRIBE--发出SETUP--发出PLAY--进入Lo ...

  4. Mac版 Intellij IDEA 激活

    第一步:修改这两个文件夹 进入跳转路径,输入 /private/etc/ 点击[前往] 同时加上: # Intellij IDEA0.0.0.0 account.jetbrains.com 第二部:在 ...

  5. PPID=1 runs as a background process, rather than being under the direct control of an interactive user

    https://en.wikipedia.org/wiki/Daemon_(computing) [后台进程,非互动] d 结尾 syslogd 系统日志记录 sshd 响应ssh连接请求 In mu ...

  6. 前端面试题(一)JS篇

    内置类型 JS 中分为七种内置类型,七种内置类型又分为两大类型:基本类型和对象(Object). 基本类型有六种: null,undefined,boolean,number,string,symbo ...

  7. TCP/IP协议之ARP寻址

    ARP协议: 前面讲了网络层的寻址是通过IP地址来做的.其实一个数据包寻址包含两个部分:1 IP寻址.2 ARP寻址. ARP寻址是用在数据链路层上的.我们上网的电脑都有网卡.那么在数据链路层的进行传 ...

  8. C++三种继承方式

    一.三种继承方式 继承方式不同,第一个不同是的是派生类继承基类后,各成员属性发生变化.第二个不同是派生类的对象能访问基类中哪些成员发生变化.表格中红色标注.

  9. Kattis - cardhand Card Hand Sorting 【暴力枚举】

    题意 给出 一个扑克牌的序列 求排成一个"有序"序列 最少的插入次数 有序是这样定义的 同一个花色的 必须放在一起 同一花色中的牌 必须是 升序 或者是 降序 然后 A 是最大的 ...

  10. Machine Learning No.9: Dimensionality reduction

    1. Principal component analysis algorithm data preprocessing 2. choosing the number of principal com ...