【Spring注解开发】组件注册-使用@Configuration和@Bean给容器中注册组件
写在前面
在之前的Spring版本中,我们只能通过写XML配置文件来定义我们的Bean,XML配置不仅繁琐,而且很容易出错,稍有不慎就会导致编写的应用程序各种报错,排查半天,发现是XML文件配置不对!另外,每个项目编写大量的XML文件来配置Spring,也大大增加了项目维护的复杂度,往往很多个项目的Spring XML文件的配置大部分是相同的,只有很少量的配置不同,这也造成了配置文件上的冗余。
项目工程源码已经提交到GitHub:https://github.com/sunshinelyz/spring-annotation
Spring IOC和DI
在Spring容器的底层,最重要的功能就是IOC和DI,也就是控制反转和依赖注入。
IOC:控制反转,将类的对象的创建交给Spring类管理创建。
DI:依赖注入,将类里面的属性在创建类的过程中给属性赋值。
DI和IOC的关系:DI不能单独存在,DI需要在IOC的基础上来完成。
在Spring内部,所有的组件都会放到IOC容器中,组件之间的关系通过IOC容器来自动装配,也就是我们所说的依赖注入。接下来,我们就使用注解的方式来完成容器组件的注册、管理及依赖、注入等功能。
在介绍使用注解完成容器组件的注册、管理及依赖、注入等功能之前,我们先来看看使用XML文件是如何注入Bean的。
通过XML文件注入JavaBean
首先,我们在工程的io.mykit.spring.bean包下创建Person类,作为测试的JavaBean,代码如下所示。
package io.mykit.spring.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
/**
* @author binghe
* @version 1.0.0
* @description 测试实体类
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
private static final long serialVersionUID = 7387479910468805194L;
private String name;
private Integer age;
}
接下来,我们在工程的resources目录下创建Spring的配置文件beans.xml,通过beans.xml文件将Person类注入到Spring的IOC容器中,配置如下所示。
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
<bean id = "person" class="io.mykit.spring.bean.Person">
<property name="name" value="binghe"></property>
<property name="age" value="18"></property>
</bean>
</beans>
到此,我们使用XML方式注入JavaBean就配置完成了。接下来,我们创建一个SpringBeanTest类来进行测试,这里,我使用的是Junit进行测试,测试方法如下所示。
@Test
public void testXmlConfig(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) context.getBean("person");
System.out.println(person);
}
运行testXmlConfig()方法,输出的结果信息如下。
Person(name=binghe, age=18)
从输出结果中,我们可以看出,Person类通过beans.xml文件的配置,已经注入到Spring的IOC容器中了。
通过注解注入JavaBean
通过XML文件,我们可以将JavaBean注入到Spring的IOC容器中。那使用注解又该如何实现呢?别急,其实使用注解比使用XML文件要简单的多,我们在项目的io.mykit.spring.plugins.register.config包下创建PersonConfig类,并在PersonConfig类上添加@Configuration注解来标注PersonConfig类是一个Spring的配置类,通过@Bean注解将Person类注入到Spring的IOC容器中。
package io.mykit.spring.plugins.register.config;
import io.mykit.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author binghe
* @version 1.0.0
* @description 以注解的形式来配置Person
*/
@Configuration
public class PersonConfig {
@Bean
public Person person(){
return new Person("binghe001", 18);
}
}
没错,通过PersonConfig类我们就能够将Person类注入到Spring的IOC容器中,是不是很Nice!!主要我们在类上加上@Configuration注解,并在方法上加上@Bean注解,就能够将方法中创建的JavaBean注入到Spring的IOC容器中。
接下来,我们在SpringBeanTest类中创建一个testAnnotationConfig()方法来测试通过注解注入的Person类,如下所示。
@Test
public void testAnnotationConfig(){
ApplicationContext context = new AnnotationConfigApplicationContext(PersonConfig.class);
Person person = context.getBean(Person.class);
System.out.println(person);
}
运行testAnnotationConfig()方法,输出的结果信息如下所示。
Person(name=binghe001, age=18)
可以看出,通过注解将Person类注入到了Spring的IOC容器中。
到这里,我们已经明确,通过XML文件和注解两种方式都可以将JavaBean注入到Spring的IOC容器中。那么,使用注解将JavaBean注入到IOC容器中时,使用的bean的名称是什么呢? 我们可以在testAnnotationConfig()方法中添加如下代码来获取Person类型下的注解名称。
//按照类型找到对应的bean名称数组
String[] names = context.getBeanNamesForType(Person.class);
Arrays.stream(names).forEach(System.out::println);
完整的testAnnotationConfig()方法的代码如下所示。
@Test
public void testAnnotationConfig(){
ApplicationContext context = new AnnotationConfigApplicationContext(PersonConfig.class);
Person person = context.getBean(Person.class);
System.out.println(person);
//按照类型找到对应的bean名称数组
String[] names = context.getBeanNamesForType(Person.class);
Arrays.stream(names).forEach(System.out::println);
}
运行testAnnotationConfig()方法输出的结果信息如下所示。
Person(name=binghe001, age=18)
person
那这里的person是啥?我们修改下PersonConfig类中的person()方法,将person()方法修改成person01()方法,如下所示。
package io.mykit.spring.plugins.register.config;
import io.mykit.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author binghe
* @version 1.0.0
* @description 以注解的形式来配置Person
*/
@Configuration
public class PersonConfig {
@Bean
public Person person01(){
return new Person("binghe001", 18);
}
}
此时,我们再次运行testAnnotationConfig()方法,输出的结果信息如下所示。
Person(name=binghe001, age=18)
person01
看到这里,大家应该有种豁然开朗的感觉了,没错!!使用注解注入Javabean时,bean在IOC中的名称就是使用@Bean注解标注的方法名称。我们可不可以为bean单独指定名称呢?那必须可以啊!只要在@Bean注解中明确指定名称就可以了。比如下面的PersonConfig类的代码,我们将person01()方法上的@Bean注解修改成@Bean("person")注解,如下所示。
package io.mykit.spring.plugins.register.config;
import io.mykit.spring.bean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author binghe
* @version 1.0.0
* @description 以注解的形式来配置Person
*/
@Configuration
public class PersonConfig {
@Bean("person")
public Person person01(){
return new Person("binghe001", 18);
}
}
此时,我们再次运行testAnnotationConfig()方法,输出的结果信息如下所示。
Person(name=binghe001, age=18)
person
可以看到,此时,输出的JavaBean的名称为person。
结论:我们在使用注解方式向Spring的IOC容器中注入JavaBean时,如果没有在@Bean注解中明确指定bean的名称,就使用当前方法的名称来作为bean的名称;如果在@Bean注解中明确指定了bean的名称,则使用@Bean注解中指定的名称来作为bean的名称。
好了,咱们今天就聊到这儿吧!别忘了给个在看和转发,让更多的人看到,一起学习一起进步!!
项目工程源码已经提交到GitHub:https://github.com/sunshinelyz/spring-annotation
写在最后
如果觉得文章对你有点帮助,请微信搜索并关注「 冰河技术 」微信公众号,跟冰河学习Spring注解驱动开发。公众号回复“spring注解”关键字,领取Spring注解驱动开发核心知识图,让Spring注解驱动开发不再迷茫。
【Spring注解开发】组件注册-使用@Configuration和@Bean给容器中注册组件的更多相关文章
- 一、Spring之组件注册-@Configuration&@Bean给容器中注册组件
xml配置方式 首先我们创建一个实体类Person public class Person { private String name; private Integer age; private St ...
- 2、组件注册-@Configuration&@Bean给容器中注册组件
2.组件注册-@Configuration&@Bean给容器中注册组件 2.1 创建maven项目 spring-annotation pom.xml文件添加 spring-context 依 ...
- Spring注解开发系列Ⅰ--- 组件注册(上)
传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...
- 浅尝Spring注解开发_自定义注册组件、属性赋值、自动装配
Spring注解开发 浅尝Spring注解开发,基于Spring 4.3.12 包含自定义扫描组件.自定义导入组件.手动注册组件.自动注入方法和参数.使用Spring容器底层组件等 配置 @Confi ...
- spring注解开发:容器中注册组件方式
1.包扫描+组件标注注解 使用到的注解如下,主要针对自己写的类 @Controller @Service @Repository @Component @ComponentScan 参考 spring ...
- Spring注解开发-全面解析常用注解使用方法之组件注册
目录 1. @Configuration 2. @ComponentScan excludeFilters includeFilters 使用自定义TypeFilter 3. @Bean @Scope ...
- Spring注解驱动开发04(给容器中注册组件的方式)
给容器中注册组件的方式 1. 组件注解标注 + 包扫描(适用于自己写的类) //控制层组件 @Controller public class PersonController { } //业务逻辑层组 ...
- 【Spring注解驱动开发】在@Import注解中使用ImportBeanDefinitionRegistrar向容器中注册bean
写在前面 在前面的文章中,我们学习了如何使用@Import注解向Spring容器中导入bean,可以使用@Import注解快速向容器中导入bean,小伙伴们可以参见<[Spring注解驱动开发] ...
- 【String注解驱动开发】如何按照条件向Spring容器中注册bean?这次我懂了!!
写在前面 当bean是单实例,并且没有设置懒加载时,Spring容器启动时,就会实例化bean,并将bean注册到IOC容器中,以后每次从IOC容器中获取bean时,直接返回IOC容器中的bean,不 ...
随机推荐
- [tgpl]go匿名函数
[tgpl]go匿名函数 0. 定义 匿名函数顾名思义是没有名字的函数, Named functions can be declared only at the package level, but ...
- nodejs上使用sql
1.首先本地要安装mysql, https://www.mysql.com/downloads/. 2.在node中连接mysql,要安装mysql驱动,也就是npm安装mysql模块:npm i m ...
- React-Redux填坑
这篇东西以后慢慢补充. Q:今天遇到一个问题是 TypeError:dispatch is not a function A:一直报这个type error,调试了好一阵,最后在tof上看到网友说co ...
- js 前端向服务器端传送文件的常用请求方式
在做项目的过程当中写到文件上传的功能,想着之前也是踩坑过来的,就在这里总结下自己常用的方法吧.我们现在一般都是通过ajax来搭起前后端数据交互的桥梁,但是大家在做到有文件需要上传的时候就会发现我们用a ...
- Django之ORM配置与单表操作
ORM数据库操作流程: 1. 配置数据库(项目同名包中settings.py和__init__.py) 2. 定义类(app包中models.py),执行建表命令(Tools---> ...
- Oracle操作时间-----摘抄而来
1.日期时间间隔操作 当前时间减去7分钟的时间 select sysdate,sysdate - interval ’7’ MINUTE from dual 当前时间减去7小时的时间 sele ...
- 基于vue+Django的简迩音乐用户界面实现
应这次软件工程课程要求,我们团队着力打造一个音乐播放器软件. 软件实现主要采用基于Vue.js+Python Django,前后端分离架构实现网页. 用户界面主要功能:呈现用户收藏歌单歌曲信息,并且提 ...
- LightOJ1197
题目链接:https://vjudge.net/problem/LightOJ-1197 题目大意: 给你 a 和 b (1 ≤ a ≤ b < 231, b - a ≤ 100000),求出 ...
- Linux 下批量杀死进程
ps aux|grep python|grep -v grep|cut -c 9-15|xargs kill -15 管道符“|”用来隔开两个命令,管道符左边命令的输出会作为管道符右边命令的输入.下面 ...
- JS中的bind 、call 、apply
# 一 .bind 特点: ### 1.返回原函数的拷贝,我们称这个拷贝的函数为绑定函数 ### 2.将函数中的this固定为调用bind方法时的第一个参数,所以称之为绑定函数.注意是名词而非动词. ...