Spring中@Component和@Bean的區別


Spring 管理Bean的方式

Spring管理Bean分為兩個部分,一個是注冊Bean,一個裝配Bean。

完成這兩個動作有三種方式,一種是使用自動配置的方式、一種是使用JavaConfig的方式,一種就是使用XML配置的方式。

@Component 把普通pojo實例化到spring容器中

@Bean 需要在配置類中使用,即類上需要加上@Configuration注解

兩者都能通過@Autowired注解自動裝配


@Compent和@Bean到底區別在哪?

在應用開發的過程中,如果想要將第三方庫中的組件裝配到你的應用中,在這種情況下,是沒有辦法在它的類上添加@Component和@Autowired注解的,因此就不能使用自動化裝配的方案了。

但是可以通過xml 或者在@Configuration配置類中通過@Bean進行配置

@Component來表示一個通用注釋,用於說明一個類是一個spring容器管理的類(再通俗易懂一點就是將要實例化的類丟到Spring容器中去)。

@Component的范圍比較廣,所有類都可以進行注解;

而@Configuration注解一般注解在類里面有@Value注解的成員變量或@Bean注解的方法,@Bean主要和@Configuration配合使用的


說到@Component注解就會想到@Controller,@Service, @Repository

@Component (把普通pojo實例化到spring容器中,相當於配置文件中的<bean id="" class=""/>)

@Controller用於標注控制層組件

@Service 用於標注業務層組件

@Repository 用於標注數據訪問組件

 

@Controller

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

@Service

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

@Repository

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

通過@Controller,@Service, @Repository這三個注解的源碼可知

@Controller,@Service, @Repository實際上都包含了@Component注解

而這三個注解比@Component帶有更多的語義,它們分別對應了控制層、服務層、持久層的類。

舉一個小例子 或許能體現上面說的作用

在SSM整合的時候 我們通常是這樣配置

spring-application.xml中

<context:component-scan base-package="com.esummer">
    <!-- 掃描注解時忽略 @Controller 注解-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

spring-mvc.xml中 

<context:component-scan base-package ="com.esummer">
   <!-- 只掃描 @Controller注解 -->
   <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

這樣 spring-application.xml文件中的掃描到除@Controller注解外的Bean 就交給Spring容器去管理

而spring-mvc.xml文件中掃描到的帶有@Controller注解的bean 交給SpringMvc容器去管理

注: Spring 容器和SpringMVC容器 不能混為一談


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM