当前位置: 首页 > 编程日记 > 正文

Spring Bean四种注入方式(Springboot环境)

阅读此文建议参考本人写的Spring常用注解:https://blog.csdn.net/21aspnet/article/details/104042826

给容器中注册组件的四种方法:


 1.@ComponentScan包扫描+组件标注注解@Component(@Controller@Service@Repository)
使用场景:自己写的代码,可以方便的加@Controller/@Service/@Repository/@Component

@SpringBootApplication
源码
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication

默认是加载和Application类所在同一个目录下的所有类,包括所有子目录下的类。

当启动类和@Component分开时,如果启动类在某个包下,需要在启动类中增加注解@ComponentScan,配置需要扫描的包名。


2.@Configuration+@Bean   
使用场景:导入的第三方包里面的组件,将其他jar包中的类(类没有Component等注解),加载到容器中。

public class User {//@Value("Tom")public String username;public User(String s) {this.username = s;}
}@Configuration
public class ImportConfig {@Beanpublic User user(){return new User("Lily");}
}@RestController
public class ImportDemoController {@Autowiredprivate User user;@RequestMapping("/importDemo")public String demo() throws Exception {String s = user.username;return "ImportDemo@SpringBoot " + s;}
}


3.@Import快速给容器中导入一个组件
         1)@Import(要导入到容器中的组件);容器中就会自动注册这个组件,id默认是全类名
         2)ImportSelector:返回需要导入的组件的全类名数组;
         3)ImportBeanDefinitionRegistrar:手动注册bean到容器中

@Import方式

public class ImportDemo {public void doSomething () {System.out.println("ImportDemo.doSomething()");}
}@Configuration
@Import({ImportDemo.class})
public class ImportConfig{
@Beanpublic User user(){return new User("Lily");}
}@RestController
public class ImportDemoController {@Autowiredprivate User user;@Autowiredprivate ImportDemo importDemo;@RequestMapping("/importDemo")public String demo() throws Exception {importDemo.doSomething();String s = user.username;return "ImportDemo@SpringBoot " + s;}
}

ImportSelector方式

//自定义逻辑返回需要导入的组件
public class MyImportSelector implements ImportSelector {//返回值,就是到导入到容器中的组件全类名//AnnotationMetadata:当前标注@Import注解的类的所有注解信息@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {// TODO Auto-generated method stub//importingClassMetadata//方法不要返回null值//当前类的所有注解Set<String> annotationTypes = importingClassMetadata.getAnnotationTypes();System.out.println("当前配置类的注解信息:"+annotationTypes);//注意不能返回null,不然会报NullPointExceptionreturn new String[]{"com.paopaoedu.springboot.bean.user01","com.paopaoedu.springboot.bean.user02"};}
}public class User01 {public String username;public User01() {System.out.println("user01...constructor");}
}public class User02 {public String username;public User02() {System.out.println("user02...constructor");}
}@Configuration
@Import({ImportDemo.class, MyImportSelector.class})
public class ImportConfig {/*** 给容器中注册组件;* 1)、包扫描+组件标注注解(@Controller/@Service/@Repository/@Component)[自己写的类]* 2)、@Bean[导入的第三方包里面的组件]* 3)、@Import[快速给容器中导入一个组件]* 		1)、@Import(要导入到容器中的组件);容器中就会自动注册这个组件,id默认是全类名* 		2)、ImportSelector:返回需要导入的组件的全类名数组;* 		3)、ImportBeanDefinitionRegistrar:手动注册bean到容器中* 4)、使用Spring提供的 FactoryBean(工厂Bean);* 		1)、默认获取到的是工厂bean调用getObject创建的对象* 		2)、要获取工厂Bean本身,我们需要给id前面加一个&,&userFactoryBean*/@Beanpublic User user(){return new User("Lily");}
}@RestController
public class ImportDemoController {@Autowiredprivate User user;@Autowiredprivate ImportDemo importDemo;@Autowiredprivate User01 user01;@RequestMapping("/importDemo")public String demo() throws Exception {importDemo.doSomething();user01.username = "user01";String s = user.username;String s1 = user01.username;return "ImportDemo@SpringBoot " + s + " " + s1;}
}

ImportBeanDefinitionRegistrar方式

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {/*** AnnotationMetadata:当前类的注解信息* BeanDefinitionRegistry:BeanDefinition注册类;* 		把所有需要添加到容器中的bean;调用* 		BeanDefinitionRegistry.registerBeanDefinition手工注册进来*/@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {boolean definition = registry.containsBeanDefinition("com.paopaoedu.springboot.bean.User01");boolean definition2 = registry.containsBeanDefinition("com.paopaoedu.springboot.bean.User02");if(definition && definition2){//指定Bean定义信息作用域都可以在这里定义;(Bean的类型,Bean。。。)RootBeanDefinition beanDefinition = new RootBeanDefinition(User03.class);//注册一个Bean,指定bean名registry.registerBeanDefinition("User03", beanDefinition);}}}
public class User03 {public String username;public User03() {System.out.println("user03...constructor");}
}

使用上和前面的类似就不举例了。


4.使用Spring提供的 FactoryBean(工厂Bean)
         1)默认获取到的是工厂bean调用getObject创建的对象
         2)要获取工厂Bean本身,我们需要给id前面加一个&
            &xxxFactoryBean 注意类名是X,这里就是小写的x?

public class UserFactoryBean implements FactoryBean<User04> {@Overridepublic User04 getObject() throws Exception {// TODO Auto-generated method stubSystem.out.println("UserFactoryBean...getObject...");return new User04("User04");}@Overridepublic Class<?> getObjectType() {// TODO Auto-generated method stubreturn User04.class;}//是否单例?//true:这个bean是单实例,在容器中保存一份//false:多实例,每次获取都会创建一个新的bean;@Overridepublic boolean isSingleton() {// TODO Auto-generated method stubreturn true;}
}public class User04 {public String username;public User04(String s) {String nowtime= DateUtil.now();username=s+" "+nowtime;}
}@Configuration
@Import({ImportDemo.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
public class ImportConfig {/*** 给容器中注册组件;* 1)、包扫描+组件标注注解(@Controller/@Service/@Repository/@Component)[自己写的类]* 2)、@Bean[导入的第三方包里面的组件]* 3)、@Import[快速给容器中导入一个组件]* 		1)、@Import(要导入到容器中的组件);容器中就会自动注册这个组件,id默认是全类名* 		2)、ImportSelector:返回需要导入的组件的全类名数组;* 		3)、ImportBeanDefinitionRegistrar:手动注册bean到容器中* 4)、使用Spring提供的 FactoryBean(工厂Bean);* 		1)、默认获取到的是工厂bean调用getObject创建的对象* 		2)、要获取工厂Bean本身,我们需要给id前面加一个&,&userFactoryBean*/@Beanpublic UserFactoryBean userFactoryBean(){return new UserFactoryBean();}@Beanpublic User user(){return new User("Lily");}
}@RestController
public class ImportDemoController {@Autowiredprivate User user;@Autowiredprivate ImportDemo importDemo;@Autowiredprivate User01 user01;@Autowiredprivate UserFactoryBean userFactoryBean;@RequestMapping("/importDemo")public String demo() throws Exception {importDemo.doSomething();user01.username = "user01";String s = user.username;String s1 = user01.username;String s4 = userFactoryBean.getObject().username;return "ImportDemo@SpringBoot " + s + " " + s1 + " " + s4;}
}@SpringBootApplication
public class SpringBootLearningApplication {public static void main(String[] args) {SpringApplication.run(SpringBootLearningApplication.class, args);AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext("com.paopaoedu.springboot.config");ImportDemo importDemo = context.getBean(ImportDemo.class);importDemo.doSomething();printClassName(context);Object bean1 = context.getBean("userFactoryBean");Object bean2 = context.getBean("userFactoryBean");System.out.println(bean1 == bean2);}private static void printClassName(AnnotationConfigApplicationContext annotationConfigApplicationContext){String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();for (int i = 0; i < beanDefinitionNames.length; i++) {System.out.println("匹配的类"+beanDefinitionNames[i]);}}
}

如果基础不够可以再看看此文:

https://blog.csdn.net/qq_27470131/category_7502799.html

相关文章:

chrome dev debug network 的timeline说明

在使用chrome的时候F12的开发者工具中有个network&#xff0c;其中对每个请求有个timeline的说明&#xff0c;当鼠标放上去会有下面的显示&#xff1a; 这里面的几个指标在说明在chrome使用文档有说明&#xff1a; 下面我用人类的语言理解下&#xff1a; Proxy 与代理服务器的连…

【MATLAB】函数句柄

在MATLAB平台中&#xff0c;对函数的调用方法分为直接调用法和间接调用法。 1、直接调用函数&#xff0c;被调用的函数通常称为子函数。一个文件中只能有一个主函数。 2、函数句柄——提供一种间接调用函数的方法。创建函数句柄需要用到操作符。 创建函数句柄的一般句法格式…

为什么企业选择年底裁员?如何选择一个正确的公司!

为什么很多企业选择年底裁员&#xff1f;首先分析一下裁员的原因&#xff1a;1、你能力不行&#xff0c;在公司吃闲饭2、减少公司成本3、公司换血&#xff0c;需要新的人才注入普通情况下&#xff0c;这些因素裁员很正常&#xff0c;只能怪自己不争气&#xff0c;成为末尾被淘汰…

springboot集成logback日志 通用logback.xml模板详解

先看Spring Boot中依赖的logback,log4j,slf4j相关Jar包 1.最简单的默认打印控制台日志 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.Reques…

【MATLAB】单元数组类型

1、概述 单元&#xff08;Cell&#xff09;数组是一种无所不包的广义数组。 组成单元数组的每个元素成为一个单元。 每一个单元可以包括任意数组&#xff0c;如数值数组&#xff0c;字符串数组&#xff0c;结构体数组或另外一个单元数组。 单元数组用花括号来创建“{ }”。…

UNITY3D拓展编辑器 - 目录

前文&#xff1a;最近在自学UNITY3D拓展器,对以上功能点做一些认知范围内的总结.目录&#xff1a;1. 属性编辑器http://weizeteng.blog.51cto.com/5604545/17744312. 工具编辑器3. 场景编辑器转载于:https://blog.51cto.com/weizeteng/1774390

程序员的你还沉浸在大公司就是螺丝钉?小公司锻炼人?错了!看完即懂

刚毕业那会经历过很多所谓创业公司&#xff0c;和很多朋友经历过画大饼&#xff0c;洗脑以及公司上市原始股这样的承诺。当你正在趟过这些谎言你就会发现&#xff0c;在这个世界上能信这些鬼话的也只有涉世未深的毕业生了。小公司里真的就是十几二十几个精英带你一路向前&#…

深入Jetty源码之Servlet框架及实现(AsyncContext、RequestDispatcher、HttpSession)

概述 Servlet是Server Applet的缩写&#xff0c;即在服务器端运行的小程序&#xff0c;而Servlet框架则是对HTTP服务器(Servlet Container)和用户小程序中间层的标准化和抽象。这一层抽象隔离了HTTP服务器的实现细节&#xff0c;而Servlet规范定义了各个类的行为&#xff0c;从…

SpringBoot conditional注解和自定义conditional注解使用

conditional注解是Springboot starter的基石&#xff0c;自动装配的时候会根据条件确定是否需要注入这个类。 含义&#xff1a;基于条件的注解。 作用&#xff1a;根据是否满足某个特定条件来决定是否创建某个特定的Bean。 意义&#xff1a;Springboot实现自动配置的关键基础…

TOPSIS算法及代码

TOPSIS的全称是“逼近于理想值的排序方法” 根据多项指标、对多个方案进行比较选择的分析方法&#xff0c;这种方法的中心思想在于首先确定各项指标的正理想值和负理想值&#xff0c;所谓正理想值是一设想的最好值&#xff08;方案&#xff09;&#xff0c;它的的各个属性值都…

django框架的基础知识点《贰》

状态保持-----session作用&#xff1a;状态保持与cookie区别&#xff1a; cookie保存在浏览器中 session&#xff1a;保存在服务器中&#xff0c;即python代码运行的那台电脑 支持配置&#xff0c;可以指定保存的位置在django中保存方案&#xff1a; 关系型数据库 内存 关系型数…

Springboot源码分析之内嵌tomcat源码分析

Springboot源码是内嵌tomcat的&#xff0c;这个和完整的tomcat还是不同。 内嵌tomcat的源码在tomcat-embed-core等3个jar包里 展开tomcat-embed-core的catalina目录 再对照下载的apache-tomcat-9.0.31源码 打开bin目录&#xff0c;看到很多库文件比如catalina.jar 再展开看看类…

spring amqp rabbitmq fanout配置

基于spring amqp rabbitmq fanout配置如下&#xff1a; 发布端 <rabbit:connection-factory id"rabbitConnectionFactory" username"guest" password"guest" host"localhost" port"5672"/> <rabbit:template id&qu…

【MATLAB】数组运算

&#xff08;这里这列举笔者不熟悉的&#xff0c;容易忘的数组运算&#xff09; 1、数组的转置 >> a[1 2 3 4 5 6 7]a 1 2 3 4 5 6 7>> bab 1234567 2、对数组的赋值 >> a([1 4])[0 0]a 0 2 3 0 5 6 73、注…

RLCenter云平台配置中心

榕力RLCenter云平台配置中心以图形界面的方式实现对云桌面系统的统一管理&#xff0c;包括用户管理、服务器管理、虚拟机管理、策略管理。可配置U盘类设备的读写权限&#xff0c;避免企业敏感信息泄密。实行数据集中存储&#xff0c;支持用户数据进行备份和恢复。 (1)云桌面性能…

SSL/TLS原理详解

本文大部分整理自网络&#xff0c;相关文章请见文后参考。 关于证书授权中心CA以及数字证书等概念&#xff0c;请移步 OpenSSL 与 SSL 数字证书概念贴 &#xff0c;如果你想快速自建CA然后签发数字证书&#xff0c;请移步 基于OpenSSL自建CA和颁发SSL证书 。 SSL/TLS作为一种互…

SpringBoot源码分析之@Scheduled

Springboot写上注解Scheduled就可以实现定时任务&#xff0c; 这里对其源码做一点分析 Service public class MyScheduled {Scheduled(cron"${time.cron}")void paoapaoScheduled() {System.out.println("Execute at " System.currentTimeMillis());} }…

【MATLAB】矩阵分析之向量和矩阵的范数运算

本片借鉴于 https://blog.csdn.net/u013534498/article/details/52674008 https://blog.csdn.net/left_la/article/details/9159949 向量范数当p1时&#xff0c;即为各个向量的元素绝对值之和 >> norm(x,1)ans 21>> xx 1 2 3 4 5 6>> no…

如何打一个FatJar(uber-jar)

如何打一个FatJar&#xff08;uber-jar&#xff09; FatJar也就叫做UberJar&#xff0c;是一种可执行的Jar包(Executable Jar)。FatJar和普通的jar不同在于它包含了依赖的jar包。 1. maven-jar-plugin 例子 <build><finalName>demo</finalName><plugins&g…

JDK源码分析 NIO实现

总列表&#xff1a;http://hg.openjdk.java.net/ 小版本&#xff1a;http://hg.openjdk.java.net/jdk8u jdk:http://hg.openjdk.java.net/jdk8u/jdk8u60/file/d8f4022fe0cd hotspot:http://hg.openjdk.java.net/jdk8u/jdk8u60/hotspot/file/37240c1019fd 调用本地native方法…

Linux进程ID号--Linux进程的管理与调度(三)

进程ID概述 进程ID类型 要想了解内核如何来组织和管理进程ID&#xff0c;先要知道进程ID的类型&#xff1a; 内核中进程ID的类型用pid_type来描述,它被定义在include/linux/pid.h中 enum pid_type {PIDTYPE_PID,PIDTYPE_PGID,PIDTYPE_SID,PIDTYPE_MAX };12345671234567PID 内核…

【MATLAB】矩阵运算之矩阵分解

矩阵分解&#xff1a;把一个矩阵分解成为矩阵连乘的形式。矩阵的分解函数cholCholesky分解cholinc稀疏矩阵的不完全Cholesky分解lu矩阵LU分解luinc稀疏矩阵的不完全LU分解qr正交三角分解svd奇异值分解gsvd一般奇异值分解schur舒尔分解 在MATLAB中线性方程组的求解主要基于四种基…

Java入门—输入输出流

File类的使用 文件是&#xff1a;文件可认为是相关记录或放在一起的数据的集合。 Java中&#xff0c;使用java.io.File类对文件进行操作 public class FileDemo {public static void main(String[] args) {String path "E:\\pdd";File f new File(path);//判断是文…

Web框架基准测试

Web Framework Benchmarks 这是许多执行基本任务&#xff08;例如JSON序列化&#xff0c;数据库访问和服务器端模板组成&#xff09;的Web应用程序框架的性能比较。每个框架都在实际的生产配置中运行。结果在云实例和物理硬件上捕获。测试实现主要是由社区贡献的&#xff0c;所…

vsftpd用户配置 No.2

在配置ftp虚拟用户的过程中&#xff0c;还有一种配置方式。yum -y install 安装vsftpdcp /etc/vsftpd/vsftpd.conf /etc/vsftpd/vsftpd.conf.bak编辑vsftpd.conf开启下列选项&#xff1a;anonymous_enableNOlocal_enableYESwrite_enableYESlocal_umask022anon_mkdir_write_enab…

【MATLAB】稀疏矩阵(含有大量0元素的矩阵)

1、稀疏矩阵的储存方式 对于稀疏矩阵&#xff0c;MATLAB仅储存矩阵所有非零元素的值及其位置&#xff08;行号和列号&#xff09;。 2、稀疏矩阵的生成 1&#xff09;利用sparse函数从满矩阵转换得到稀疏矩阵函数名称表示意义sparse(A)由非零元素和下标建立稀疏矩阵A。如果A已是…

httpTomcat

Tomcat是web应用服务器的一种 转载于:https://juejin.im/post/5beaf7e451882517165d91d1

memcached(二)事件模型源码分析

在memcachedd中&#xff0c;作者为了专注于缓存的设计&#xff0c;使用了libevent来开发事件模型。memcachedd的时间模型同nginx的类似&#xff0c;拥有一个主进行&#xff08;master&#xff09;以及多个工作者线程&#xff08;woker&#xff09;。 流程图 在memcached中&…

【MATLAB】MATLAB的控制流

1、if-else-end if expressioncommands1 elseif expression2commands2 ... else commandsn end 2、switch-case switch valuecase1 test1%如果value等于test1&#xff0c;执行command1&#xff0c;并结束此结构command1case2 test2command2...case3 testkcommandk otherw…

Linux查看本机端口

查看指定的端口 # lsof -i:port 查看所有端口 # netstat -aptn 安装telnet #yum install -y telnet.x86_64 #telnet ip 端口