@Import的用法

news2024/9/21 12:41:20

官方定义:

https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core

Using the @ImportAnnotation

Much as the <import/> element is used within Spring XML files to aid in modularizing 
configurations, the @Import annotation allows for loading @Bean definitions from another 
configuration class, as the following example shows:

@Import注解的作用与Spring的XML配置文件中的<import/>元素一样:都是用于帮助建立模块化配置,@Import可以从其他配置类中加载 @Bean的定义,如下所示:

@Configuration
public class ConfigA {

    @Bean
    public A a() {
        return new A();
    }
}

@Configuration
@Import(ConfigA.class)
public class ConfigB {

    @Bean
    public B b() {
        return new B();
    }
}
Now, rather than needing to specify both ConfigA.class and ConfigB.class when instantiating the 
context, only ConfigB needs to be supplied explicitly, as the following example shows:

如上代码,在类ConfigB中添加了注解 @Import(ConfigA.class) ,那么,在初始化上下文(如下所示)时就不需要同时指定类 ConfigA.class 和 类ConfigB.class 了,只需要显示的指定类 ConfigB即可,下面是例子:

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

    // now both beans A and B will be available...
    A a = ctx.getBean(A.class);
    B b = ctx.getBean(B.class);
}

如上,初始化上下文ctx时只需要使用ConfigB,同样可以通过 ctx.getBean(A.class)获取在ConfigA中配置的A实例(bean)

This approach simplifies container instantiation, as only one class 
needs to be dealt with, rather than requiring you to remember a 
potentially large number of @Configuration classes during construction.

这种方法简化了容器的初始化,在初始化构造时,只需要处理一个类,而不必记住潜在的大量的@Configuration配置类。

小结: 以上是针对通过:

 ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);

这种方式获取bean实例时

A a = ctx.getBean(A.class);
    B b = ctx.getBean(B.class);

通过@Import注解时,可以简化容器的初始化!

但是,如果直接通过@Autowired注入的方式获取容器中的bean,@Import还有用武之地吗?

因为只要容器中有对应的bean存在,@Autowired就会将其注入过来!既然这样,那@Import似乎没有什么作用了!, 如下示例:

package com.xl.test.logtest.utils;

public class Pen {
	
	private String name = "this is apple!";
	
	public Pen () {
		System.out.println("+++constructing pen object+++");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
package com.xl.test.logtest.utils;

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

@Configuration
public class Eraser {
	
	@Bean
	public Pen genPenBean() {
		return new Pen();
	}
	
}

以上代码,在容器启动时会初始化一个Pen对象/实例/bean

package com.xl.test.logtest.utils;

public class Apple {
	
	private String name = "this is apple!";
	
	public Apple() {
		System.out.println("***constructing Apple object***");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}
package com.xl.test.logtest.utils;

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

@Configuration
public class Tree {
	
	@Bean
	public Apple genAppleBean() {
		return new Apple();
	}
	
}

以上代码,在容器启动时会初始化一个Apple对象/实例/bean

编写测试类:
通过@Autowired直接获取想要的bean

package com.xl.test.logtest.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xl.test.logtest.utils.Apple;
import com.xl.test.logtest.utils.Pen;

@RestController
public class LogTestController {
	
	private static Logger logger = LoggerFactory.getLogger(LogTestController.class);
	
	@Autowired
	Pen pen;
	
	@Autowired
	Apple apple;
	
	@GetMapping("/log")
	public String log() {
		Assert.notNull(pen, "对象为空!");
		Assert.notNull(apple, "对象为空!");
		return "pen : "+ pen.getName()+ " ; apple: "+apple.getName();
	}
}

启动项目:完成bean的创建
在这里插入图片描述
浏览器访问,验证:
在这里插入图片描述

断言Assert 并没有抛出异常信息,说明pen和apple对象都不为null,同时浏览器也输出了pen和apple的名字。

给类Eraser加上@Import(Tree.class)或者给类Tree加上@Import(Eraser.class),项目运行情况和测试结果没有任何变化!@Import注解没有起作用!验证略。

实际上,针对@Autowired注解的场景不是没有用,而是@Import是有它特定的使用场景的:@Import可以引入外部的bean。

何为外部的bean??

外部bean指的是:Spring容器启动时不会自动扫描的类并生成的bean。

Spring容器启动时会去扫描哪些类? : 主启动类所在包及子包下面的带有@Component注解的类!

而@Import注解就是用于引入外部的bean的, 示例如下:

在外部新建一个类Paper,如下:
在这里插入图片描述

package com.other.pkg;

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

import com.xl.test.logtest.utils.Color;
import com.xl.test.logtest.utils.Picture;

@Configuration
public class Paper {

	@Bean
	public Color getColorBean() {
		System.out.println("********************color bean init********************");
		return new Color();
	}
	
	@Bean 
	public Picture getPictureBean() {
		System.out.println("********************picture bean init********************");
		return new Picture();
	}
	
}

在不使用@Import注解时,在测试类中注入外部类Paper中的bean :

package com.xl.test.logtest.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.other.pkg.Paper;
import com.xl.test.logtest.utils.Apple;
import com.xl.test.logtest.utils.Color;
import com.xl.test.logtest.utils.Pen;
import com.xl.test.logtest.utils.Picture;

@RestController
public class LogTestController {
	
	private static Logger logger = LoggerFactory.getLogger(LogTestController.class);
	
	@Autowired
	Paper paper;
	
	@Autowired
	Color color;
	
	@Autowired
	Picture picture;
	
	@GetMapping("/log")
	public String log() {
		return "paper : "+ paper+ " ; color: "+color.getName()+" ; picture: "+picture.getSize();
	}
	
	
}

启动项目,观察:
在这里插入图片描述

在主启动类的包或子包下新建一个带@Component的类,同时,加上@Import注解:

package com.xl.test.logtest.utils;

import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import com.other.pkg.Paper;

@Import(Paper.class)
@Component
public class ForImport {

}

启动项目,测试:

在这里插入图片描述

如上所示,项目启动成功,并完成外部类中相关bean的初始化; 访问项目再次测试:
在这里插入图片描述

同样,获取到了外部类中的bean。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/188821.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

一文详解ARP报文格式及工作原理

ARP&#xff08;地址解析协议&#xff09;作用&#xff1a;将目的IP解析为目的MAC&#xff0c;用于二层帧结构的目标MAC封装&#xff0c;数据必须封装为帧才能够被网卡发送出去&#xff0c;帧中必须包含MAC。报文格式&#xff1a;ARP报文不能穿越路由器&#xff0c;不能被转发到…

基于飞桨实现钢铁企业废钢判级迈入智能化道路

目前&#xff0c;国家“双碳”战略与“数据智能”环境正驱动着钢铁企业废钢判级迈入智能化道路。针对生产过程中带来高能耗和高污染问题&#xff0c;企业通过使用飞桨用友废钢智能判级系统&#xff0c;助力提升自身经济效益和安全生产水平。 建设背景 目前&#xff0c;国家“双…

如何在IDEA中创建Web项目

&#x1f44c; 棒棒有言&#xff1a;也许我一直照着别人的方向飞&#xff0c;可是这次&#xff0c;我想要用我的方式飞翔一次&#xff01;人生&#xff0c;既要淡&#xff0c;又要有味。凡事不必太在意&#xff0c;一切随缘&#xff0c;缘深多聚聚&#xff0c;缘浅随它去。凡事…

QT入门Buttons之QToolButton

目录 一、界面布局介绍 1、布局器中的位置及使用 2、控件的界面属性 2.1对象名称和大小设置 2.2对象文本设置和鼠标箭头更改 2.3、扁平化样式 二、属性功能介绍 1、显示箭头属性 2、按钮风格 3、添加默认action属性 三、Demo展示 此文为作者原创&#xff0c;转载请标…

Web前端:提高React Native应用程序性能的技巧

不可否认&#xff0c;React Native是开发混合应用的未来。它提供了可扩展性、灵活性、速度、敏捷性、成本效益和卓越的性能。难怪这么多成功的公司依赖React Native来构建他们的应用程序。毕竟&#xff0c;在互联网时代&#xff0c;每个企业都需要一个高性能的应用程序来满足客…

PCB如何进行阻抗设计经验总结

&#x1f3e1;《总目录》 目录1&#xff0c; 什么是阻抗匹配2&#xff0c;为何要阻抗匹配3&#xff0c;阻抗设计经验1&#xff0c; 什么是阻抗匹配 阻抗是指电路中两点间电阻&#xff0c;电感和电容的总称。而阻抗匹配是指&#xff0c;传输线及传输线两端的电子元器件的输入或输…

Canvas(HTML 5 元素)之绘制曲线图形

文章目录参考描述模板圆形圆形半圆形互补弧形arc()arcTo()二次贝塞尔曲线三次贝塞尔曲线参考 项目描述搜索引擎BingCanvas 中文网CanvasRenderingContext2DW3schoolHTML Canvas 参考手册从 0 到 1&#xff1a;HTML 5 Canvas 动画开发莫振杰 描述 项目描述Edge109.0.1518.70 (…

1.Java基础入门

目录 一.java概述 1.1 java语言发展史 1.2 为什么用Java 1.3 Java能做什么 1.4 Java技术体系 二.Java快速入门 2.1 如何使用Java 2.2 JVM&#xff0c;JRE&#xff0c;JDK 2.2.1 JVM 2.2.2 JRE 2.2.3 JDK 2.3 JDK的下载和安装 2.3.1 JDK的下载 2.3.2 JDK的安装 2.3.3 如何验证JD…

git版本回滚详解

写在前面&#xff1a;本文图片中出现的git st, git co分别是git status和git checkout的简写&#xff0c;使用中可以自行设置git config --global alias.st statusgit config --global alias.co checkout查看git配置文件 vim ~/.gitconfig1 工作区内的回滚操作当工作区的文件发…

Android 传感器概述(二)

Android 传感器概述&#xff08;二&#xff09;Android 传感器概述&#xff08;二&#xff09;运动传感器使用重力传感器使用线性加速度计使用旋转矢量传感器使用有效运动传感器使用计步器传感器使用步测器传感器使用原始数据使用加速度计使用陀螺仪使用未经校准的陀螺仪Androi…

【数据结构】动图详解单向链表

目录 1.什么是链表 1.问题引入 2. 链表的概念及结构 3. 问题解决 2.单向链表接口的实现 1.接口1&#xff0c;2---头插&#xff0c;尾插 2. 接口3&#xff0c;4---头删&#xff0c;尾删 3. 接口5---查找 4. 接口6&#xff0c;7---插入&#xff0c;删除 5. 接口8---打印 6. 注意…

CVE-2021-36934提权复现

CVE-2021-369342021年7 月 20 日&#xff0c;微软确认了一个新的本地提权漏洞(CVE-2021-36934)&#xff0c;被称为HiveNightmare。该漏洞由于Windows中多个系统文件的访问控制表(ACL)过于宽松&#xff0c;使得任何标准用户都可以从系统卷影副本中读取包括SAM、SYSETM、SECURITY…

Windows系统运行iOS设备管理软件iMazing2023

iMazing2023免费版是一款运行在Windows系统上的iOS设备管理软件&#xff0c;软件功能非常强大&#xff0c;界面简洁清晰&#xff0c;操作方便快捷&#xff0c;设计的非常有人性化&#xff0c;iMazing官方版为用户提供了多种设备管理功能&#xff0c;每一位用户都能以自己的形式…

MyISAM和InnoDB存储引擎的区别

目录前言存储引擎区别事务外键表单的存储数据查询效率数据更新效率如何选择前言 MyISAM和InnoDB是使用MySQL最常用的两种存储引擎&#xff0c;在5.5版本之前默认采用MyISAM存储引擎&#xff0c;从5.5开始采用InnoDB存储引擎。 存储引擎 存储引擎是&#xff1a;数据库管理系统…

小白如何快速入门Verilog HDL ?一文为你讲解清楚

在学习的过程中&#xff0c;无论学什么都不可能一蹴而就。都是从一个初步认识到慢慢了解再到精通掌握的过程&#xff0c;学习Verilog HDL语法也是一样的道理&#xff0c;首先你要清楚什么是Verilog HDL&#xff0c;然后结合实践再遵从理论&#xff0c;这样后面的学习才能理解的…

P1359 租用游艇

# 租用游艇 ## 题目描述 长江游艇俱乐部在长江上设置了 $n$ 个游艇出租站 $1,2,\cdots,n$。游客可在这些游艇出租站租用游艇&#xff0c;并在下游的任何一个游艇出租站归还游艇。游艇出租站 $i$ 到游艇出租站 $j$ 之间的租金为 $r(i,j)$&#xff08;$1\le i\lt j\le n$&#xf…

MPLS实验(1.31)

目标&#xff1a; 一、首先为公网的每个路由器配置对应的ip和环回并且用OSPF进行动态选路 r2&#xff1a; [r2]int gi 0/0/2 [r2-GigabitEthernet0/0/2]ip add 23.1.1.1 24 [r2-GigabitEthernet0/0/2]int lo0 [r2-LoopBack0]ip add 2.2.2.2 24 r3&#xff1a; [r3]int gi 0…

Oracle的学习心得和知识总结(十)|Oracle数据库PL/SQL语言循环控制语句之LOOP语句技术详解

目录结构 注&#xff1a;提前言明 本文借鉴了以下博主、书籍或网站的内容&#xff0c;其列表如下&#xff1a; 1、参考书籍&#xff1a;《Oracle Database SQL Language Reference》 2、参考书籍&#xff1a;《PostgreSQL中文手册》 3、EDB Postgres Advanced Server User Guid…

yolov5篇---yolov5训练pt模型并转换为rknn模型,部署在RK3588开发板上——从训练到部署全过程

yolov5训练pt模型并转换为rknn模型&#xff0c;部署在RK3588开发板上——从训练到部署全过程一、任务介绍二、实验过程2.1 使用正确版本的yolov5进行训练(平台&#xff1a;x86机器ubuntu22.04系统)2.2 best.pt转换为best.onnx(平台&#xff1a;x86机器ubuntu22.04系统)2.3 best…

2023年西安Java培训机构十强榜单出炉,快来看看哪家榜上有名~

关于“西安Java培训机构哪家好&#xff1f;”“如何选择适合自己的Java培训机构&#xff1f;”这类问题常常出现网络上&#xff0c;其实关于这类问题没有统一的答案&#xff0c;一千个人有一千个哈姆雷特&#xff0c;每个人关注的重点不一样&#xff0c;需求更是不同&#xff0…