2020-08-26

@Bean和@Component之间的区别与联系

===>
Spring管理Bean分为两个部分,一个是注册Bean,一个装配Bean。@Bean和@Component两者的目的是一样的,都是注册bean到Spring容器中,都可通过@Autowired进行装配。
简单来说:
@Component 把普通pojo实例化到spring容器中,即用于说明一个类作为spring容器管理的类。@Component的范围比较广,所有类都可以进行注解(但若想将第三方的类变成组件,而又没有源代码,也就没办法使用@Component进行自动配置,这时候就需要使用XML或@Bean结合@Configuation进行自动配置)。使用@Component注解的类
若结合配置类,则必须添加自动扫描注解:
@ComponentScan(basePackages = “com.xxx.yyy”)
或不使用纯注解方式,在xml文件中进行添加
<context:component-scan base-package=“com.dxz.demo”/>

而相对应的@Bean无法在类上进行声明,一般结合配置类在方法上进行声明。即告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。

举个例子:
1,@Bean的应用:

—Bean类—

public class TestBean {
	xxx
}

—配置类—

@Configuration
public class TestConfiguration {

		 @Bean     
	    public TestBean testBean() {
	        return new TestBean();
	    }
	
}

—测试类—

public class TestMain {
    public static void main(String[] args) {

        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

         //获取bean
        TestBean tb = (TestBean) context.getBean("testBean");
        
	}
}

对应的
2,@Component的应用

—Bean类—

@Component
public class TestBean {
	xxx
}

—配置类—

@Configuration
@ComponentScan(basePackages = "com.xxx.yyy") 
public class TestConfiguration {

}

—测试类—

public class TestMain {
    public static void main(String[] args) {

        // @Configuration注解的spring容器加载方式,用AnnotationConfigApplicationContext替换ClassPathXmlApplicationContext
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfiguration.class);

         //获取bean
        TestBean tb = (TestBean) context.getBean("testBean");
        
	}
}

注:@Component所细分的@Controller,@Service, @Repository遵循的原则同上。
当我们在进行SSM整合的时候 我们通常
spring-application.xml文件中的扫描到除@Controller注解外的Bean 就交给Spring容器去管理
而spring-mvc.xml文件中扫描到的带有@Controller注解的bean 交给SpringMvc容器去管理(也可以使用纯注解)
(Spring 容器和SpringMVC容器 不能混为一谈)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值