Spring中Bean及@Bean的理解
Bean在Spring和SpringMVC中⽆所不在,将这个概念内化很重要,下⾯分享⼀下我的想法:
⼀、Bean是啥
1、Java⾯向对象,对象有⽅法和属性,那么就需要对象实例来调⽤⽅法和属性(即实例化);
2、凡是有⽅法或属性的类都需要实例化,这样才能具象化去使⽤这些⽅法和属性;
3、规律:凡是⼦类及带有⽅法或属性的类都要加上注册Bean到Spring IoC的注解;
4、把Bean理解为类的代理或代⾔⼈(实际上确实是通过反射、代理来实现的),这样它就能代表类拥有该拥有的东西了
5、我们都在微博上@过某某,对⽅会优先看到这条信息,并给你反馈,那么在Spring中,你标识⼀个@符号,那么Spring就会来看看,并且从这⾥拿到⼀个Bean或者给出⼀个Bean
⼆、注解分为两类:
1、⼀类是使⽤Bean,即是把已经在xml⽂件中配置好的Bean拿来⽤,完成属性、⽅法的组装;⽐如@A
utowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的⽅式获取Bean;
2、⼀类是注册Bean,@Component , @Repository , @ Controller , @Service , @Configration这些注解都是把你要实例化的对象转化成⼀个Bean,放在IoC容器中,等你要⽤的时候,它会和上⾯的@Autowired , @Resource配合到⼀起,把对象、属性、⽅法完美组装。
三、@Bean是啥?resource和autowired注解的区别
1、原理是什么?先看下源码中的部分内容:
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呢?这个我也不知道,下⾯我给个例⼦,⼀起探讨⼀下吧:
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.Class().getName().hashCode);
System.out.Class().getName().hashCode);
return new Apple();
}
}
/*
*测试类
*/
@RunWith(BlockJUnit4ClassRunner.class)
public class Config {
public Config(){
super("l");
}
@Test
public void test(){
的是⼀个Apple类实例对象
}
}
从上⾯的例⼦也印证了我上⾯的总结的内容:
1、凡是⼦类及带属性、⽅法的类都注册Bean到Spring中,交给它管理;
2、@Bean ⽤在⽅法上,告诉Spring容器,你可以从下⾯这个⽅法中拿到⼀个Bean
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论