Spring整合SpringMVC-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会自动开启

原文地址:https://www.cnblogs.com/wwzyy/p/5559400.html