Spring中@Bean与@Configuration
一、Spring中Bean及@Bean的理解[1]
Bean在Spring和SpringMVC中无所不在,将这个概念内化很重要,下面分享一下我的想法:
一、Bean是啥
1、Java面向对象,对象有方法和属性,那么就需要对象实例来调用方法和属性(即实例化);
2、凡是有方法或属性的类都需要实例化,这样才能具象化去使用这些方法和属性;
3、规律:凡是子类及带有方法或属性的类都要加上注册Bean到Spring IoC的注解;
4、把Bean理解为类的代理或代言人(实际上确实是通过反射、代理来实现的),这样它就能代表类拥有该拥有的东西了
5、我们都在微博上@过某某,对方会优先看到这条信息,并给你反馈,那么在Spring中,你标识一个@符号,那么Spring就会来看看,并且从这里拿到一个Bean或者给出一个Bean
二、注解分为两类:
1、一类是使用Bean,即是把已经在xml文件中配置好的Bean拿来用,完成属性、方法的组装;比如@Autowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean;
2、一类是注册Bean,@Component , @Repository , @ Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成一个Bean,放在IoC容器中,等你要用的时候,它会和上面的@Autowired , @Resource配合到一起,把对象、属性、方法完美组装。
三、@Bean是啥?
1、原理是什么?先看下源码中的部分内容:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
Indicatesby the <h3>Overview</h3> <p>Thethis annotation similarin the example: <pre class="code"> @Bean public MyBean // return obj; }</pre> |
意思是@Bean明确地指示了一种方法,什么方法呢——产生一个bean的方法,并且交给Spring容器管理;从这我们就明白了为啥@Bean是放在方法的注释上了,因为它很明确地告诉被注释的方法,你给我产生一个Bean,然后交给Spring容器,剩下的你就别管了
2、记住,@Bean就放在方法上,就是产生一个Bean,那你是不是又糊涂了,因为已经在你定义的类上加了@Configration等注册Bean的注解了,为啥还要用@Bean呢?这个我也不知道,下面我给个例子,一起探讨一下吧:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.edu.fruit; //定义一个接口 public interface Fruit<T>{ //没有方法}/**定义两个子类*/package com.edu.fruit; @Configuration public class Apple implements Fruit<Integer>{//将Apple类约束为Integer类型}package com.edu.fruit; @Configuration public class GinSeng implements Fruit<String>{//将GinSeng}/**业务逻辑类*/package com.edu.service; @Configuration public class FruitService @Autowired private Apple @Autowired private GinSeng //定义一个产生Bean的方法 @Bean(name="getApple") public Fruit<?> System.out.println(apple.getClass().getName().hashCode); System.out.println(ginseng.getClass().getName().hashCode); return new Apple();}}/**测试类*/@RunWith(BlockJUnit4ClassRunner.class)public class Config public Config(){ super("classpath:spring-fruit.xml"); } @Test public void test(){ super.getBean("getApple");//这个Bean从哪来,从上面的@Bean下面的方法中来,返回 的是一个Apple类实例对象 }} |
从上面的例子也印证了我上面的总结的内容:
1、凡是子类及带属性、方法的类都注册Bean到Spring中,交给它管理;
2、@Bean 用在方法上,告诉Spring容器,你可以从下面这个方法中拿到一个Bean
二、Spring中基于Java的配置@Configuration和@Bean用法[2]
spring中为了减少xml中配置,可以生命一个配置类(例如SpringConfig)来对bean进行配置。
一、首先,需要xml中进行少量的配置来启动Java配置:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
- xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
- <context:component-scan base-package="SpringStudy.Model">
- </context:component-scan>
- </beans>
二、定义一个配置类
用@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。
代码如下:
- package SpringStudy;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import SpringStudy.Model.Counter;
- import SpringStudy.Model.Piano;
- @Configuration
- public class SpringConfig {
- @Bean
- public Piano piano(){
- return new Piano();
- }
- @Bean(name = "counter")
- public Counter counter(){
- return new Counter(12,"Shake it Off",piano());
- }
- }
三、基础类代码
Counter:
- package SpringStudy.Model;
- public class Counter {
- public Counter() {
- }
- public Counter(double multiplier, String song,Instrument instrument) {
- this.multiplier = multiplier;
- this.song = song;
- this.instrument=instrument;
- }
- private double multiplier;
- private String song;
- @Resource
- private Instrument instrument;
- public double getMultiplier() {
- return multiplier;
- }
- public void setMultiplier(double multiplier) {
- this.multiplier = multiplier;
- }
- public String getSong() {
- return song;
- }
- public void setSong(String song) {
- this.song = song;
- }
- public Instrument getInstrument() {
- return instrument;
- }
- public void setInstrument(Instrument instrument) {
- this.instrument = instrument;
- }
- }
Piano类
- package SpringStudy.Model;
- public class Piano {
- private String name="Piano";
- private String sound;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getSound() {
- return sound;
- }
- public void setSound(String sound) {
- this.sound = sound;
- }
- }
四、调用测试类
- package webMyBatis;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- import SpringStudy.Model.Counter;
- public class SpringTest {
- public static void main(String[] args) {
- //ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/bean.xml");// 读取bean.xml中的内容
- ApplicationContext annotationContext = new AnnotationConfigApplicationContext("SpringStudy");
- Counter c = annotationContext.getBean("counter", Counter.class);// 创建bean的引用对象
- System.out.println(c.getMultiplier());
- System.out.println(c.isEquals());
- System.out.println(c.getSong());
- System.out.println(c.getInstrument().getName());
- }
- }
注意:如果是在xml中配置beans和bean的话,或者使用自动扫描调用的话,代码为
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/bean.xml");// 读取bean.xml中的内容
Counter c = ctx.getBean("counter", Counter.class);// 创建bean的引用对象
五、运行结果
12.0
false
Shake it Off
Piano
Reference:
[1] Bossen, Spring中Bean及@Bean的理解, http://www.cnblogs.com/bossen/p/5824067.html
[2] 欲穷千里目,更上一层楼, Spring中基于Java的配置@Configuration和@Bean用法, http://blog.csdn.net/vvhesj/article/details/47661001
Spring中@Bean与@Configuration的更多相关文章
- Spring中Bean及@Bean的理解
Spring中Bean及@Bean的理解 Bean在Spring和SpringMVC中无所不在,将这个概念内化很重要,下面分享一下我的想法: 一.Bean是啥 1.Java面向对象,对象有方法和属性, ...
- spring 中bean学习笔记
spring 中bean 一.bean的定义和应用 1. bean 形象上类似于getXX()和setXX()的一种. 2. 由于java是面向对象的,类的方法和属性在使用中需要实例化. 3. 规律: ...
- Spring入门(五):Spring中bean的作用域
1. Spring中bean的多种作用域 在默认情况下,Spring应用上下文中所有的bean都是以单例(singleton)的形式创建的,即不管给定的一个bean被注入到其他bean多少次,每次所注 ...
- Spring中Bean命名源码分析
Spring中Bean命名源码分析 一.案例代码 首先是demo的整体结构 其次是各个部分的代码,代码本身比较简单,不是我们关注的重点 配置类 /** * @Author Helius * @Crea ...
- java开发两年,连Spring中bean的装配都不知道?你怎么涨薪啊
Spring 1.1.1.1 创建一个bean package com.zt.spring; public class MyBean { private String userName; privat ...
- Spring中Bean的作用域、生命周期
Bean的作用域.生命周期 Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).protot ...
- Spring中Bean的实例化
Spring中Bean的实例化 在介绍Bean的三种实例化的方式之前,我们首先需要介绍一下什么是Bean,以及Bean的配置方式. 如果 ...
- Spring中Bean的命名问题(id和name区别)及ref和idref之间的区别
Spring中Bean的命名 1.每个Bean可以有一个id属性,并可以根据该id在IoC容器中查找该Bean,该id属性值必须在IoC容器中唯一: 2.可以不指定id属性,只指定全限定类名,如: & ...
- (转)Spring中Bean的命名问题(id和name区别)及ref和idref之间的区别
Spring中Bean的命名 1.每个Bean可以有一个id属性,并可以根据该id在IoC容器中查找该Bean,该id属性值必须在IoC容器中唯一: 2.可以不指定id属性,只指定全限定类名,如: & ...
随机推荐
- 2019-07-30 ThinkPHP文件上传
文件上传就是获取到待上传文件的临时路径,把它移动到服务器下的相应文件夹中. 文件上传,必须在表单中的form标签中写入:enctype="multipart/form-data" ...
- webpack面试题
1.webpack的核心概念 Entry:入口,Webpack进行打包的起始点(文件) Output:出口,webpack编译打包生成的bundle(打包文件) Loader:模块加载(转换)器,将非 ...
- JavaScript 之 事件(详解)
一.注册事件的三种方式 1.直接事件方式 语法格式: 变量名.on事件名 = function() {} 注意:这种方式无法给同一对象的同一事件注册多个事件处理函数 2.addEventListene ...
- QTGraphics-View拖拽以及鼠标指针操作
因为QGraphicsView继承自QWidget,它也提供了像QWidget那样的拖拽功能. 另外,为了方便,Graphics View框架也为场景以及每个item提供拖拽支持.当视图接收到拖拽事件 ...
- 为什么共进电子会选择APS系统?(APS应用案例)
企业介绍 深圳市共进电子股份有限公司(下文简称,共进电子)自1998年创始,以 “发展企业,培养人才,回馈社会”为宗旨,拥有“T&W”商标.2015年2月登陆上交所A股市场,证券代码为6031 ...
- XmlDocument.load 读文件报异常:文件正被其它线程使用,解决方法
string filePath = Form1.getProjectFilePath(); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocu ...
- restframework详细
1.写视图的方法 1.1第一种:原始APIView url(r'^login/$',account.LoginView.as_view()), from rest_framework.views im ...
- Educational Codeforces Round 67 D. Subarray Sorting
Educational Codeforces Round 67 D. Subarray Sorting 传送门 题意: 给出两个数组\(a,b\),现在可以对\(a\)数组进行任意次排序,问最后能否得 ...
- Beta冲刺(7/7)——2019.5.28
所属课程 软件工程1916|W(福州大学) 作业要求 Beta冲刺(7/7)--2019.5.28 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪万里 ...
- PHP的简单了解
PHP 标识符/关键字/数据类型 标识符:其实标识符就是变量的名称,函数与类的名称也是标识符.PHP中标识符的规则: 1.标识符可以是任意长度的字母.数字.下划线,且不得以数字开头. 2.PHP中标识 ...