Spring中 @Bean和@Component 注解的区别和作用

      Spring中 @Bean和@Component 注解的区别和作用

 

一、两个注解的作用

1、@Component: 作用于类上,告知Spring,为这个类创建Bean。

2、@Bean:主要作用于方法上,告知Spring,这个方法会返回一个对象,且要注册在Spring的上下文中。通常方法体中包含产生Bean的逻辑。 相当于 xml文件的中<bean>标签。

1、org.springframework.stereotype.Component 
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
      
}

2、org.springframework.context.annotation.Bean
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    
}

 

 

二、区别

1、Component :作用于类上,通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。(@Controller、@Service、@Repository )

2、@Bean: 作用于方法或注解上,通常这个方法中定义产生这个Bean的逻辑。

3、@Bean注解和 <bean> 标签
<bean id="user" class="xxx.User">
    <property name="id" value="11" ></property>
</bean>

@Configuration
public class UserConfig {
	@Bean
	public User getUser() {
		User user =new User();
		user.setId(11);
		return user;
	}
}

 

三、联系

1、作用都是一样的,都是注册bean到Spring容器中。

2、引用第三方库中的类需要装配到Spring容器时,则只能通过@Bean来实现。如下:

 

@Bean
public OneService getService(status) {
    case (status)  {
        when 1:
                return new serviceImpl1();
        when 2:
                return new serviceImpl2();
        when 3:
                return new serviceImpl3();
    }
}

 (以上这个例子是无法用Component以及其具体实现注解(Controller、Service、Repository)来实现的。)

 

3、Spring帮助我们管理Bean分为两个部分 (引用这里):

一个是注册Bean(@Component , @Repository , @Controller , @Service , @Configration), 

一个装配Bean(@Autowired , @Resource,可以通过byTYPE(@Autowired)、byNAME(@Resource)的方式获取Bean)。 完成这两个动作有三种方式,一种是使用自动配置的方式、一种是使用JavaConfig的方式,一种就是使用XML配置的方式。

 

四、总结

1、@Component和@Bean都是用来注册Bean并装配到Spring容器中,但是Bean比Component的自定义性更强。可以实现一些Component实现不了的自定义加载类。

2、@Bean主要用于第三方类库的加载到Spring Bean中,之前通过xml中的<baen>标签来实现,现在可直接在类中实现。 比如: Spring Boot中添加 Swagger 、 Shiro 、 注册Servlet、Filter、Listener 等等。

 

 

参考资料:Spring中@Component与@Bean的区别

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值