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会自动开启
本文来自博客园,作者:wzyy,转载请注明原文链接:https://www.cnblogs.com/wwzyy/p/5559400.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix