一、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
Indicates
that a method produces a bean to be managed 
by the
Spring container.
 
 <h3>Overview</h3>
 
 <p>The
names and semantics of the attributes to 
this annotation
are intentionally
 similar
to those of the {@code <bean/>} element 
in the
Spring XML schema. For
 example:
 
 <pre class="code">
     @Bean
     public MyBean
myBean() {
         //
instantiate and configure MyBean obj
         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
类约束为String类型
 
}
/*
*业务逻辑类
*/
package com.edu.service;
       @Configuration
       public class FruitService
{
          @Autowired
          private Apple
apple;
          @Autowired
          private GinSeng
ginseng;
    //定义一个产生Bean的方法
       @Bean(name="getApple")
       public Fruit<?>
getApple(){
       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配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  10. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
  11. <context:component-scan base-package="SpringStudy.Model">
  12. </context:component-scan>
  13. </beans>

二、定义一个配置类

用@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。

代码如下:

  1. package SpringStudy;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import SpringStudy.Model.Counter;
  5. import SpringStudy.Model.Piano;
  6. @Configuration
  7. public class SpringConfig {
  8. @Bean
  9. public Piano piano(){
  10. return new Piano();
  11. }
  12. @Bean(name = "counter")
  13. public Counter counter(){
  14. return  new Counter(12,"Shake it Off",piano());
  15. }
  16. }

三、基础类代码

Counter:

  1. package SpringStudy.Model;
  2. public class Counter {
  3. public  Counter() {
  4. }
  5. public  Counter(double multiplier, String song,Instrument instrument) {
  6. this.multiplier = multiplier;
  7. this.song = song;
  8. this.instrument=instrument;
  9. }
  10. private double multiplier;
  11. private String song;
  12. @Resource
  13. private Instrument instrument;
  14. public double getMultiplier() {
  15. return multiplier;
  16. }
  17. public void setMultiplier(double multiplier) {
  18. this.multiplier = multiplier;
  19. }
  20. public String getSong() {
  21. return song;
  22. }
  23. public void setSong(String song) {
  24. this.song = song;
  25. }
  26. public Instrument getInstrument() {
  27. return instrument;
  28. }
  29. public void setInstrument(Instrument instrument) {
  30. this.instrument = instrument;
  31. }
  32. }

Piano类

  1. package SpringStudy.Model;
  2. public class Piano {
  3. private String name="Piano";
  4. private String sound;
  5. public String getName() {
  6. return name;
  7. }
  8. public void setName(String name) {
  9. this.name = name;
  10. }
  11. public String getSound() {
  12. return sound;
  13. }
  14. public void setSound(String sound) {
  15. this.sound = sound;
  16. }
  17. }

四、调用测试类

  1. package webMyBatis;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  4. import SpringStudy.Model.Counter;
  5. public class SpringTest {
  6. public static void main(String[] args) {
  7. //ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/bean.xml");// 读取bean.xml中的内容
  8. ApplicationContext annotationContext = new AnnotationConfigApplicationContext("SpringStudy");
  9. Counter c = annotationContext.getBean("counter", Counter.class);// 创建bean的引用对象
  10. System.out.println(c.getMultiplier());
  11. System.out.println(c.isEquals());
  12. System.out.println(c.getSong());
  13. System.out.println(c.getInstrument().getName());
  14. }
  15. }

注意:如果是在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

最新文章

  1. MineCraft note
  2. C#动态创建和动态使用程序集、类、方法、字段等
  3. Power BI for Office 365(一)移动端应用
  4. 配置Office 365单点登录过程中的一些注意事项
  5. Dynamics AX 2012 R2 窗体系列 - 在窗体上修改字段时所触发的方法及其顺序
  6. 分区还原工具(DiskGenius)
  7. bokeh-scala
  8. docker报Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.19)
  9. robotframe中使用report,设置路径带有时间戳
  10. MySQL 约束、表连接、表关联、索引
  11. u-boot(四)命令实现
  12. url加密和解密
  13. QT QHttpMultiPart上传图片
  14. javaScript 二分查找
  15. Problem B. Full Binary Tree
  16. Unity3D Shader 学习笔记(二):ShaderLab的结构和基本属性
  17. Error generating final archive: Unable to get debug signature key
  18. Auto Layout简单应用——以编码的方式实现Auto Layout自动布局(二)
  19. 第三天:Servlet运行原理
  20. 奇妙的 clip-path 几何图形

热门文章

  1. vue组件5 组件和v-for指令
  2. webpack面试题
  3. Axios的简单用法
  4. 【Python】列表推导式
  5. Golang: 接收GET和POST参数
  6. 数据分组统计函数族——apply族用法与心得
  7. php中的闭包类
  8. 【比赛游记】(THUPC,CTS,APIO)2019四连爆蛋记
  9. 追光的人beta冲刺总结
  10. 项目Beta冲刺 用户试用报告