首页 文章资讯内容详情

Spring整合SpringMVC-SpringMVC注入Spring的bean

2026-06-01 2 花语

本文内容纲要:

一、Spring和SpringMVC两个IOC容器有什么关系呢?

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

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

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

或者,

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

二、把bean放入IOC的方式

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

如:

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

2·两种可以使用自动扫描的方式配置,这种比较省事

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

自动扫描com.wzy包下的所有文件,如果类上标记了

@Controller(控制层);@Service(服务层);@Repository(持久层dao);@Component(普通组件)

importorg.springframework.stereotype.Component;

importorg.springframework.stereotype.Controller;

importorg.springframework.stereotype.Repository;

importorg.springframework.stereotype.Service;

会自动把这个类放入IOC容器。

注意:@Controller@Repository@Service这3个注解都是基于@Component。 不信看源码: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public@interfaceComponent{ /** *Thevaluemayindicateasuggestionforalogicalcomponentname, *tobeturnedintoaSpringbeanincaseofanautodetectedcomponent. *@returnthesuggestedcomponentname,ifany */ publicabstractStringvalue()default""; } @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component//看这里 public@interfaceController{ /** *Thevaluemayindicateasuggestionforalogicalcomponentname, *tobeturnedintoaSpringbeanincaseofanautodetectedcomponent. *@returnthesuggestedcomponentname,ifany */ Stringvalue()default""; } 其他两个注解类似,不一一列出了

开启了context:component-scan后会自动开启

之后可以通过@Autowired自动注入

三、从IOC中获取bean

1·手动获取,配置比较清晰

在类里这样写

classTest{

privatePersonperson;

publicvoidsetPerson(Personperson){

this.person=person;

}

}

配置文件里

这样就把person属性注入进去了

2·自动注入(@Autowired)

类里这样写:

@Autowired

privatePersonperson;

这样如果IOC里有Person,就会自动注入进去

使用@Autowired的前提是开启

如果不开启的话,自动注入不起作用

如果配置文件中已经配置了context:component-scan的话,那么AutowiredAnnotationBeanPostProcessor会自动开启

本文内容总结:

原文链接:https://www.cnblogs.com/wwzyy/p/5559400.html