Spring入门之五-------SpringIoC之通过注解实现
一、准备工作
创建一个Class注解@Configuration,如下例子:
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@ComponentScan("com.imooc.springClass5.annotation") // 开启包扫描
public class BeanConfiguration { }
我们创建了一个Class(类名可随意)并注解了@Configuration,这样可以将该Class看做一个spring的xml文件。同时我们增加了@ComponentScan注解开启了包扫描,在扫描包及其子包下面的所有被注解了@Component、@Controller、@Service、@Repository的Class会自动被实例化。
测试代码类似之前通过加载xml格式文件:
@Test
public void testBean() throws Exception {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
// 省略其他代码...
}
二、通过构造方法实例化Bean
直接在Class上面注解@Component即可,当然也可以注解@Controller、@Service、@Repository。@Component为通用型注解,@Controller、@Service、@Repository则各具有一定的业务含义,一般的@Controller被标注在Controller层、@Service被标注在Service层、@Repository被标注在Dao层。
@Component // 通过构造方法实例化bean
public class Bean1 {
}
@Component // 通过构造方法实例化bean
public class Bean2 {
private final Bean1 bean1;
@Autowired // 自动注入Bean1的实例
public Bean2(Bean1 bean1) {
this.bean1 = bean1;
}
}
在上面的两个例子中,Bean1有默认构造方法,则Spring会通过默认构造方法实例化Bean1;Bean2的构造方法包含参数Bean1,所以Spring在实例化Bean2的时候回在IoC容器中寻找Class为Bean1的实例并注入到该构造方法中以完成对Bean2的实例化。其中:@Autowired表示自动注入。
三、注入Bean
1. 通过方法注入Bean
(1)可通过构造方法注入Bean,如上面Bean2的例子
(2)可通过Set方法注入Bean,例如:
@Component // 通过构造方法实例化bean
public class Bean2 {
private Bean1 bean1;
@Autowired // 自动注入Bean1的实例
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
// get方法省略......
}
2. 通过属性注入Bean
@Component // 通过构造方法实例化bean
public class Bean2 {
@Autowired // 自动注入Bean1的实例
private Bean1 bean1;
// get/set方法省略......
}
3. 集合类型Bean的注入
(1)直接注入集合实例
@Component // 通过构造方法实例化bean
public class Bean {
private List<String> stringList;
private Map<String, String> stringMap; public List<String> getStringList() {
return stringList;
} @Autowired // 通过set方法注入bean
public void setStringList(List<String> stringList) {
this.stringList = stringList;
} public Map<String, String> getStringMap() {
return stringMap;
} @Autowired // 通过set方法注入bean
public void setStringMap(Map<String, String> stringMap) {
this.stringMap = stringMap;
}
}
当然,同时也需要在IoC容器中存在List的Bean和Map的Bean,那么我们怎么实例化这两个Bean呢?修改最开始我们创建的BeanConfiguration即可:
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@ComponentScan("com.imooc.springClass5.annotation") // 开启包扫描
public class BeanConfiguration { @Bean() // 实例化一个List
public List<String> stringList() {
List<String> list = new ArrayList<String>();
list.add("aaaaa");
list.add("bbbbb");
return list;
} @Bean() // 实例化一个Map
public Map<String, String> stringMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("aaa", "111");
map.put("bbb", "222");
return map;
}
}
通常情况下,@Bean用来实例化那些我们不能修改源码的Class,或者需要多次实例化的Class。而@Component系列的四个注解用来实例化我们自己创建的且只需要一次实例化的Class。
那么小伙伴会问了,在上面的例子中,如果我们实例化了多个List或多个Map,Spring在为Bean注入的时候会给我注入哪个呢?答案是:Spring会报错给你看!解决办法就是在通过@Bean和@Component系列实例化Bean的时候指定BeanId,通过@Autowired注入Bean的时候同时通过@Qualifier指定要注入的BeanId。那么上面的例子可以改成:
@Component // 通过构造方法实例化bean
public class Bean {
// ... 省略部分代码
@Autowired // 通过set方法注入bean
@Qualifier("stringList") // 指定注入id为stringList的bean
public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
// ... 省略部分代码
@Autowired // 通过set方法注入bean
@Qualifier("stringMap") // 指定注入id为mapString的bean
public void setStringMap(Map<String, String> stringMap) {
this.stringMap = stringMap;
}
}
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@ComponentScan("com.imooc.springClass5.annotation") // 开启包扫描
public class BeanConfiguration { @Bean("stringList") // 实例化一个List,id为stringList
public List<String> stringList() {
// ... 省略部分代码
} @Bean("stringMap") // 实例化一个Map,id为stringMap
public Map<String, String> stringMap() {
// ... 省略部分代码
}
}
(2)将多个泛型的实例注入到集合
Spring支持将多个泛型的实例注入到集合,举例如下:
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@ComponentScan("com.imooc.springClass5.annotation") // 开启包扫描
public class BeanConfiguration { @Bean("integer1") // 实例化一个Integer,id为integer1
public Integer integer1() {
return 10001;
} @Bean("integer2") // 实例化一个Integer,id为integer2
public Integer integer2() {
return 10002;
}
}
在上面的代码中,我们实例化了两个Integer类型数据,并为每个实例设定了beanId。然后:
@Component // 通过构造方法实例化bean,类似的还有@Controller、@Service、@Repository
public class Bean {
private List<Integer> integerList;
private Map<String, Integer> integerMap; public List<Integer> getIntegerList() {
return integerList;
} @Autowired // 通过set方法注入bean,将注入所有已经交由IoC容器管理的Integer类型的bean
public void setIntegerList(List<Integer> integerList) {
this.integerList = integerList;
} public Map<String, Integer> getIntegerMap() {
return integerMap;
} @Autowired // 通过set方法注入bean,将注入所有已经交由IoC容器管理的Integer类型的bean,其中beanId即为键值
public void setIntegerMap(Map<String, Integer> integerMap) {
this.integerMap = integerMap;
}
}
上面两个@Autowired会将我们在BeanConfiguration中创建的两个Integer类型的Bean全部注入到集合当中,当注入到Map类型(键为String类型)时,beanId即作为键值注入。
测试代码:
@Test
public void testBean() throws Exception {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
System.out.println("bean.getIntegerList() = " + bean.getIntegerList());
System.out.println("bean.getIntegerMap() = " + bean.getIntegerMap());
}
输出:
bean.getIntegerList() = [10001, 10002]
bean.getIntegerMap() = {integer1=10001, integer2=10002}
当然,如果你想控制泛型实例在List中的顺序,可以通过增加@Order注解的方式实现:
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@ComponentScan("com.imooc.springClass5.annotation")
public class BeanConfiguration { @Bean("integer1") // 实例化一个Integer,id为integer1
@Order(5) // 该注解可决定这个bean被注入到list时候的顺序,可以不连续
public Integer integer1() {
return 10001;
} @Bean("integer2") // 实例化一个Integer,id为integer2
@Order(2) // 该注解可决定这个bean被注入到list时候的顺序,可以不连续
public Integer integer2() {
return 10002;
}
}
则输出结果即变为:
bean.getIntegerList() = [10002, 10001]
bean.getIntegerMap() = {integer1=10001, integer2=10002}
4. String、Integer等类型直接赋值
String、Integer等类型直接赋值可用@Value实现,例如:
@Component // 通过构造方法实例化bean,类似的还有@Controller、@Service、@Repository
public class Bean {
private String string; public String getString() {
return string;
} @Value("zzzzz") // 直接将zzzzz这个值注入进去
public void setString(String string) {
this.string = string;
}
}
四、设定Bean的作用域scope
可直接通过@Scope来实现,例如:
@Component // 通过构造方法实例化bean
@Scope("singleton") // 设定bean作用域
public class Bean1 {
}
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@ComponentScan("com.imooc.springClass5.annotation")
public class BeanConfiguration {
@Bean // 实例化一个Bean1
@Scope("singleton") // 设定bean作用域
public Bean1 bean1() {
return new Bean1();
}
}
五、Bean的懒加载
可直接通过@Lazy实现,例如:
@Component // 通过构造方法实例化bean
@Lazy // 开启懒加载
public class Bean1 {
}
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@Lazy // 开启懒加载
public class BeanConfiguration {
@Bean // 实例化一个Bean1
@Scope("singleton") // 设定bean作用域
public Bean1 bean1() {
return new Bean1();
}
}
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@Lazy // 开启懒加载
public class BeanConfiguration {
}
注意第三段代码中的@Lazy注解,这意味着在该Configuration中实例化的Bean都将默认为懒加载模式
六、Bean别名
Spring允许一个Bean拥有多个BeanId,但暂时只能在@Bean中实现,@Component系列四个注解暂不支持,@Bean举例如下:
@Configuration // 该注解可理解为将当前class等同于一个xml文件
public class BeanConfiguration {
@Bean({"bean1_1", "bean1_2"}) // 实例化一个Bean1设定其拥有两个BeanId,分别为bean1_1和bean1_2
public Bean1 bean1() {
return new Bean1();
}
}
七、引入其他注解了@Configuration的Class 或 其他xml文件格式配置
可直接通过@Import实现,例如:
@Configuration // 该注解可理解为将当前class等同于一个xml文件
@Import(BeanConfiguration1.class)
@ImportResource("classpath:spring.xml")
public class BeanConfiguration {
}
并且BeanConfiguration1无需注解@Configuration
public class BeanConfiguration1 {}
八、方法注入
可能存在如下场景:Class A 的某个方法依赖于Class B的实例,Class A使用scope=singleton单例模式,但是Class A每次执行方法的时候都希望获取一个新的Class B的实例,这个时候就用到了方法注入。举例:
@Component // 通过构造方法实例化bean
@Scope("prototype") // 设定bean作用域
public class Bean3 { }
@Component // 通过构造方法实例化bean,类似的还有@Controller、@Service、@Repository
public abstract class Bean {
@Lookup
protected abstract Bean3 createBean3();
public void printBean3() {
System.out.println("createBean3().toString() = " + createBean3().toString());
}
}
测试代码:
public class BeanTest {
@Test
public void testBean() throws Exception {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
Bean bean = context.getBean(Bean.class);
bean.printBean3();
bean.printBean3();
bean.printBean3();
}
}
输出:
createBean3().toString() = com.imooc.springClass5.annotation.Bean3@1722011b
createBean3().toString() = com.imooc.springClass5.annotation.Bean3@57ad2aa7
createBean3().toString() = com.imooc.springClass5.annotation.Bean3@5b3f61ff
可以看到Bean.printBean3()方法每次拿到的Bean3都是不同的实例
九、@PostConstruct和@PreDestroy
如果需要在Bean实例化完成之后或需要在Bean销毁之前执行一些逻辑,
- 可通过@PostConstruct和@PreDestroy实现。
- 可通过@Bean的initMethod和destroyMethod实现。
@Component // 通过构造方法实例化bean
public class Bean1 { public Bean1() {
System.out.println(this.getClass().getSimpleName() + ":" + this.toString() + " has been created");
} @PostConstruct
public void postConstruct() {
System.out.println(this.getClass().getSimpleName() + ":postConstruct()");
} @PreDestroy
public void preDestroy() {
System.out.println(this.getClass().getSimpleName() + ":preDestroy()");
}
}
public class Bean4 {
public Bean4() {
System.out.println(this.getClass().getSimpleName() + ":" + this.toString() + " has been created");
}
public void init() {
System.out.println(this.getClass().getSimpleName() + ":init()");
}
public void destroy() {
System.out.println(this.getClass().getSimpleName() + ":destroy()");
}
}
@Configuration // 该注解可理解为将当前class等同于一个xml文件
public class BeanConfiguration { @Bean(initMethod = "init", destroyMethod = "destroy")
public Bean4 bean4() {
return new Bean4();
}
}
测试:
@Test
public void testBean() throws Exception {
final AbstractApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
System.out.println("=================context has bean created=====================");
Bean1 bean1 = context.getBean("bean1", Bean1.class);
System.out.println("bean1 = " + bean1);
Bean4 bean4 = context.getBean("bean4 ", Bean4.class);
System.out.println("bean4 = " + bean4);
context.close();
}
输出:
Bean1:com.imooc.springClass5.annotation.Bean1@415b0b49 has been created
Bean1:postConstruct()
Bean4:com.imooc.springClass5.annotation.Bean4@7ef27d7f has been created
=================context has bean created=====================
Bean4:init()
Bean4:destroy()
Bean1:preDestroy()
十、SpringIoC容器本身接口实例注入
Spring支持我们直接注入其相关接口实例,例如:ApplicationContext、BeanFactory、Environment、ResourceLoader、ApplicationEventPublisher、MessageSource接口及其实现类,举例其中一个说明:
@Component // 通过构造方法实例化bean,类似的还有@Controller、@Service、@Repository
public class Bean { private ApplicationContext context; public ApplicationContext getContext() {
return context;
} @Autowired // 可直接将ApplicationContext注入进来,也可以注入BeanFactory、Environment、ResourceLoader、ApplicationEventPublisher、MessageSource及其实现类
public void setContext(ApplicationContext context) {
this.context = context;
}
}
Spring入门之五-------SpringIoC之通过注解实现的更多相关文章
- Spring入门(6)-使用注解装配
Spring入门(6)-使用注解装配 本文介绍如何使用注解装配. 0. 目录 使用Autowired 可选的自动装配 使用Qualifier选择 1. 使用Autowired package com. ...
- Spring入门(三)— AOP注解、jdbc模板、事务
一.AOP注解开发 导入jar包 aop联盟包. aspectJ实现包 . spring-aop-xxx.jar . spring-aspect-xxx.jar 导入约束 aop约束 托管扩展类和被扩 ...
- Spring入门(二)— IOC注解、Spring测试、AOP入门
一.Spring整合Servlet背后的细节 1. 为什么要在web.xml中配置listener <listener> <listener-class>org.springf ...
- Spring (二)SpringIoC和DI注解开发
1.Spring配置数据源 1.1 数据源(连接池)的作用 数据源(连接池)是提高程序性能出现的 事先实例化数据源,初始化部分连接资源 使用连接资源时从数据源中获取 使用完毕后将连接资源归还给数据源 ...
- Spring入门之四-------SpringIoC之其他知识点
一.懒加载 public class Bean1 { public Bean1() { System.out.println(this.getClass().getSimpleName() + &qu ...
- Spring入门之三-------SpringIoC之Scopes
一.singleton和prototype public class Bean1 { public Bean1() { System.out.println(this.getClass().getSi ...
- Spring入门注解版
参照博文Spring入门一,以理解注解的含义. 项目结构: 实现类:SpringHelloWorld package com.yibai.spring.helloworld.impl; import ...
- 【Spring Framework】Spring入门教程(三)使用注解配置
本文主要介绍四个方面: (1) 注解版本IOC和DI (2) Spring纯注解 (3) Spring测试 (4) SpringJDBC - Spring对数据库的操作 使用注解配置Spring入门 ...
- SSM(spring mvc+spring+mybatis)学习路径——1-1、spring入门篇
目录 1-1 Spring入门篇 专题一.IOC 接口及面向接口编程 什么是IOC Spring的Bean配置 Bean的初始化 Spring的常用注入方式 专题二.Bean Bean配置项 Bean ...
随机推荐
- EC20的指令
AT+QURCCFG="urcport","usbat" :当设置在主串口时且用主串口进行AT交互时开机会收到一串状态的信息,默认USBAT就不会 AT+IPR ...
- Excel使用小技巧
1.Excel随机设置单元格的内容为整数0或1: 在单元格中写公式: =ROUND(RAND(),0) 2.设置某个单元格的值为1或0,根据其他3个单元格的值为0或1来确定: 在该单元格中写公式: ...
- C++ — 后缀表达式转表达式树
2018-07-21 16:57:26 update 建立表达式树的基本思路:方法类似由下而上建立堆的思想,所以时间复杂度为O(n),这样算法就会变得很简单,只用考虑处理需要入栈的节点和栈中的节点即可 ...
- Windows API—CreateEvent—创建事件
事件是一个允许一个线程在某种情况发生时,唤醒另外一个线程的同步对象.事件告诉线程何时去执行某一给定的任务,从而使多个线程流平滑,CreateEvent是创建windows事件的意思,作用主要用在判断线 ...
- 6(计算机网络) 交换机与VLAN
拓扑结构是怎么形成的? 我们常见到的办公室大多是一排排的桌子,每个桌子都有网口,一排十几个座位就有十几个网口,一个楼层就会有几十个甚至上百个网口.如果算上所有楼层,这个场景自然比你宿舍里的复杂多了.具 ...
- PHP pclzip.php 解压中文乱码
修改 pclzip中方法privExtractFile 代码 if ($p_path != '') { $p_entry['filename'] = $p_path."/".$p_ ...
- HTML的几个注意点
一.HTML 1.HTML5有哪些新特性?新增的标签有哪些? 新特性: 语义标签——语义化标签使得页面的内容结构化,见名知义 增强型表单——拥有多个新的表单 Input 输入类型.这些新特性提供了更好 ...
- java并发(二):初探syncronized
参考博客 Java多线程系列--"基础篇"04之 synchronized关键字 synchronized基本规则 第一条 当线程访问A对象的synchronized方法和同步块的 ...
- docker学习笔记-06:自定义DockerFile生成镜像
一.自定义centos的DockerFile 1.从阿里源里拉的centos镜像新建的容器实例中,没有vim编辑器和ifconfig命令,所以自定义centos的DockerFile,创建自己想要的镜 ...
- 转:Nginx的超时keeplive_timeout配置详解
https://blog.csdn.net/weixin_42350212/article/details/81123932 Nginx 处理的每个请求均有相应的超时设置.如果做好这些超时时间的限定, ...