SpringMVC注入Spring的bean


一、Spring和SpringMVC兩個IOC容器有什么關系呢?

Spring的IOC容器包含了SpringMVC的IOC,即SpringMVC配置的bean可以調用Spring配置好的bean,反之則不可以。

如果SpringMVC想通過@Autowired注入Spring容器里的屬性,即使Spring配置文件已經配置好了。

 <context:component-scan base-package="com.wzy"></context:component-scan>

或者<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> ,

SpringMVC配置文件中也得需要從新配置

 

二、把bean放入IOC的方式

1·在配置文件中手動配置,此方式配置比較清晰明了

如:<bean id="test" class="com.wzy.controller.Test"></bean>

就把com.wzy.controller.Test放入了IOC容器里啦

2·兩種可以使用自動掃描的方式配置,這種比較省事

 <context:component-scan base-package="com.wzy"></context:component-scan>

自動掃描com.wzy包下的所有文件,如果類上標記了

@Controller(控制層);@Service(服務層);@Repository(持久層dao);@Component(普通組件)

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

會自動把這個類放入IOC容器。

注意:@Controller@Repository@Service這3個注解都是基於@Component。
不信看源碼:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any
     */
    public abstract String value() default "";

}


@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component   //看這里
public @interface Controller {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any
     */
    String value() default "";

}

其他兩個注解類似,不一一列出了

 

開啟了context:component-scan后會自動開啟

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

之后可以通過@Autowired自動注入

 

三、從IOC中獲取bean

1·手動獲取,配置比較清晰

在類里這樣寫

class Test{

  private Person person;
  public void setPerson(Person person) {
  this.person = person;
  }

}

配置文件里

<bean id="test" class="com.wzy.controller.Test">
<property name="person" ref="person"></property>
</bean>

這樣就把person屬性注入進去了

2·自動注入(@Autowired)

類里這樣寫:

@Autowired

private Person person;

這樣如果IOC里有Person ,就會自動注入進去

使用@Autowired的前提是開啟

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

如果不開啟的話,自動注入不起作用

如果配置文件中已經配置了context:component-scan的話,那么AutowiredAnnotationBeanPostProcessor會自動開啟

 


免責聲明!

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



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