
Spring使用注解管理bean
发布日期:2021-05-07 09:14:14
浏览次数:21
分类:原创文章
本文共 1980 字,大约阅读时间需要 6 分钟。
Spring使用注解管理bean
-
通过注解分别创建Dao、Service、controller(servlet),通过给bean上添加某些注解,可以快速将bean加入到ioc容器;
/*Spring有四个类,在任何类加上任意注解都能快速将这个组件加入ioc容器的管理中 @Controller:控制器,推荐给controller层的组件使用 @Service:业务逻辑,推荐给service层件使用 @Repository:数据库,推荐给Dao层使用 @Component:组件,给不属于以上层使用 步骤: (1)给要添加的组件上标四个注解的任何一个 (2)告诉spring自动扫描加了注解的组件,依赖context名称空间 (3)一定要导入aop包spring-aop-4.0.0.RELEASE.jar*/package com.atguigu.dao;import org.springframework.stereotype.Repository;@Repositorypublic class BookDao { }
package com.atguigu.service;import org.springframework.stereotype.Service;@Service("bookService01")//可以这样自定义id名字public class BookService { }
package com.atguigu.servlet;import org.springframework.stereotype.Controller;@Controller@Scope(value="prototype") //这样写可以开启多实例public class BookServlet { }
-
使用配置文件开启组件扫描
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 开启组件扫描,依赖context名称空间 base-package:指定扫描的基础包,把基础包及它下面的包的所有类,自动扫描进ioc容器中 --> <context:component-scan base-package="com.atguigu"></context:component-scan></beans>
-
测试
package com.atguigu.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.atguigu.dao.BookDao;public class AnnotationTest { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); @Test public void annotation(){ //id默认就是首字母小写 BookDao bookDao = context.getBean("bookDao",BookDao.class); BookDao bookDao2 = context.getBean("bookDao",BookDao.class); System.out.println(bookDao==bookDao2);//true } }
发表评论
最新留言
留言是一种美德,欢迎回访!
[***.207.175.100]2025年04月04日 04时09分20秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
STM32F407单片机ADC采样定时器触发事件分布
2019-03-04
LWIP协议socket通信设置发送接收超时等待时间
2019-03-04
RT -Thread Studio开发环境下使用W5500做TCP客户端
2019-03-04
Warning: The core is locked up的解决办法
2019-03-04
奔涌吧 后浪!!! 哔哩哔哩 何冰
2019-03-04
【JVM系列】JDK 内置工具
2019-03-04
JAVA 基础与进阶系列索引 -- JDK 源码学习系列 -- 并发
2019-03-04
网络编程系列索引 -- Linux 网络编程索引
2019-03-04
网络编程系列索引 -- JAVA 网络编程系列
2019-03-04
【JDK源码分析系列】ArrayBlockingQueue源码分析
2019-03-04
【网络通信 -- 直播】音视频常见封装格式 -- MEPG2 TS
2019-03-04
【网络通信 -- 直播】音视频常见封装格式 -- FLV
2019-03-04
【C/C++基础进阶系列】C/C++ 对象模型 -- 类基础知识总结(三)
2019-03-04
【C/C++基础进阶系列】C/C++ 对象模型 -- 对象语义
2019-03-04
基于FPGA的HDMI信号采样原理
2019-03-04
Spring 与使用STOMP消息
2019-03-04
AngularJS ng-class、ng-style
2019-03-04
Linux 查看系统语言
2019-03-04
十 一、C语言创建桌面程序:单选按钮、复选框和分组框控件
2019-03-04