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 ...
随机推荐
- Android之Builder对话框的一些常用方式
原文: http://blog.csdn.net/kkfdsa132/article/details/6322835 Android为我们提供几种对话框,主要有:AlertDialog.Progres ...
- overlay rate
1.导入nii.img文件,三维矩阵 2.模版矩阵和网络矩阵对应位置元素相乘 .* 3.生成位置为0的新矩阵 cc=(nii_new==0); 4.两个矩阵的非零元素个数 t1=length(ni ...
- 34 java 文件过滤 FileFilter
package com.da.tool.util; import org.apache.commons.io.filefilter.RegexFileFilter; import java.io.Fi ...
- 怎么在高清屏上画一条0.5px的边
怎么在高清屏上画一条0.5px的边呢?0.5px相当于高清屏物理像素的1px.这样的目的是在高清屏上看起来会更细一点,效果会更好一点,例如更细的分隔线. 理论上px的最小单位是1,但是会有几个特例,高 ...
- Jmeter JDBC配置
前提条件,驱动包mysql-connector-java-5.1.38-bin.jar要放到本机Java路径:C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext ...
- .net设计模式
1.单例模式 public sealed class Singleton { static intance=null; static readonly object padlock=new objec ...
- F: Fabulous Race Between Tortoise And Rabbit 扩展欧几里得
http://oj.jxust.edu.cn/contest/Problem?id=1561&pid=5 题目描述 经历了上次的惨败,兔子一直心怀不满,又策划了一场比赛,但这次不再是简单的跑步 ...
- ORM常用字段及查询
目录 ORM常用字段及参数 创建表 ORM常用字段 ORM字段参数 ORM表关系创建 ForeignKey OneToOneField ManyToManyField 多对多三种创建方式 单表查询 q ...
- burpsuite下载安装及基本配置
jdk安装 根据电脑安装对应jdk版本 点此下载jdk 下载完成得到如下exe文件 配置Java环境变量 计算机右键-->属性-->高级系统设置-->环境变量 点击环境变量--> ...
- .net高手:forms验证中中<forms loginUrl="" defaultUrl="">defaulturl和loginurl的区别
.net高手:forms验证中中<forms loginUrl="" defaultUrl="">defaulturl和loginurl的区别 d ...