当前位置: 首页 > news >正文

Spring基础注解使用

Spring基础注解使用

一、概述

注解替换xml的方案:

常见替换:

二、实验

2.1实验Component替换Bean标签(以userDao3为例)

a.写标好@Component注解

packagecom.itheima.dao.impl;importcom.itheima.dao.UserDao;importorg.springframework.stereotype.Component;//在注解开发中,属性只有一个,且是叫value的时候可以省略//<bean class="com.itheima.dao.impl.UserDaoImpl3" id="userDao3"/>@Component("userDao3")publicclassUserDaoImpl3implementsUserDao{@Overridepublicvoidshow(){}}
//// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//packageorg.springframework.stereotype;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Indexedpublic@interfaceComponent{Stringvalue()default"";}

将注解放在相关类的上面实际上就可以省略了全限制名,然后@Component底层又是只有一个value属性,可以是直接省略“value”了

b.配置组件扫描:

<?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.xsd "><!--加入组件扫描,扫描指定包及其子包下使用注解的类。将其放到Spring容器--><context:component-scan base-package="com.itheima"/></beans>

测试:

packagecom.itheima;importorg.springframework.context.support.ClassPathXmlApplicationContext;publicclassApplicationContextTest3{publicstaticvoidmain(String[]args){ClassPathXmlApplicationContextapplicationContextTest2=newClassPathXmlApplicationContext("applicationContext3.xml");Objectobject=applicationContextTest2.getBean("userDao3");Objectobject2=applicationContextTest2.getBean("userService3");System.out.println(object2);System.out.println(object);}}

结果:

拓展:

@Component()的三个注解:

当然了,这几个标签是等价的吗,只不过我们在开发的时候遵循这个规范,见名知意。

//// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//packageorg.springframework.stereotype;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;importorg.springframework.core.annotation.AliasFor;@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic@interfaceService{@AliasFor(annotation=Component.class)Stringvalue()default"";}

从@Service的源码里面可以看到其本质还是 @Component(),只不过我们遵循相关的规范,一般只有在Bean不属于上面的三层的情况下我们才使用@Component()注入。

2.2其他标签

1.@Scope():

//// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//packageorg.springframework.context.annotation;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;importorg.springframework.core.annotation.AliasFor;@Target({ElementType.TYPE,ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceScope{@AliasFor("scopeName")Stringvalue()default"";@AliasFor("value")StringscopeName()default"";ScopedProxyModeproxyMode()defaultScopedProxyMode.DEFAULT;}

也是只有value属性(scopeName和value是通用的,互为别名,所以默认是一个属性),直接设置为单例模式:

@Scope("singleton")

2.@Lazy():

//// Source code recreated from a .class file by IntelliJ IDEA// (powered by FernFlower decompiler)//packageorg.springframework.context.annotation;importjava.lang.annotation.Documented;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target({ElementType.TYPE,ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.PARAMETER,ElementType.FIELD})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceLazy{booleanvalue()defaulttrue;}

延迟加载,直接设置为true

@Lazy(true)

​ 延迟加载可以实现加载完配置文件后还没有加载Bean,知道调用getBean方法时才加载Bean:

2.@PreDestroy()和destroy()

@PostConstructpublicvoidinit(){System.out.println("UserDaoImpl3对象初始化了...");}@PreDestroypublicvoiddestroy(){System.out.println("UserDaoImpl3对象销毁了...");}

测试:

packagecom.itheima;importorg.springframework.context.support.ClassPathXmlApplicationContext;publicclassApplicationContextTest3{publicstaticvoidmain(String[]args){ClassPathXmlApplicationContextapplicationContextTest2=newClassPathXmlApplicationContext("applicationContext3.xml");Objectobject=applicationContextTest2.getBean("userDao3");Objectobject2=applicationContextTest2.getBean("userService3");System.out.println(object2);System.out.println(object);// 要显示地关闭才会执行销毁方法,Spring容器不知道自己要挂掉了applicationContextTest2.close();}}

结果:

2.3Spring依赖注入相关注解

2.3.1概述
2.3.2具体操作

1.@Value():

@Value("WangLei")privateStringusername;
privateStringusername;@Value("WangLei")publicvoidsetUsername(Stringusername){this.username=username;}

两种方式都可以注入,上面的几个标签都是这样,就不再逐一演示了。但是说像@Value()用在法上的情形是比较少的,主要是用在Spring的框架表达式当中,例如之前我们集成Mybatis的时候注入数据库信息:

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/mybatis jdbc.username=root jdbc.password=root
@Value("${jdbc.driver}")privateStringusername;

一般是这样用得多。

2.@Autowired():

@AutowiredprivateUserServiceImpl3userDao;

3.@Qualifier()

@Autowired@Qualifier("userDao")privateUserDaouserDao;

4.@Resource()

@Resource(name="userDao3")privateUserDaouserDao;
2.3.3@Autowired拓展

@Autowired注入在方法上时候是比配参数列表的:

@Autowiredpublicvoidxxx(UserDaoImpl3userDao){System.out.println("xxx:"+userDao);}@Autowiredpublicvoidyyy(List<UserDao>userDaoList){System.out.println("yyy:"+userDaoList);}

需要UserDaoImpl3就注入UserDaoImpl3,需要UserDao集合有几个就注入几个。

http://www.jsqmd.com/news/377876/

相关文章:

  • 2026年哈尔滨四轮定位选购攻略,哪些服务值得选 - myqiye
  • IoT 固件中的 Web 漏洞挖掘:模拟运行、解包与逆向分析
  • 基于java的物联网智能监控平台设计与开发毕业设计源码
  • 基于STM32的AD7190四通道不连续采集模式实现代码
  • 408真题解析-2010-39-计算机网络-拥塞窗口/滑动窗口
  • 横评后发现!万众偏爱的降AIGC软件 —— 千笔·降AI率助手
  • 基于java的移动端数据可视化系统设计与实现毕设源码
  • 基于java的在线教育平台课程管理系统研究毕设源码
  • 基于java的区块链技术实现数字货币交易系统毕设
  • 基于java的企业资源计划(ERP)系统开发与改进毕设
  • 毕业论文神器 8个AI论文工具测评:专科生高效写作+格式规范全攻略
  • 律师咨询|基于java+ vue律师咨询系统(源码+数据库+文档)
  • 2026年靠谱的数码印花法兰绒/素色法兰绒公司口碑推荐哪家靠谱 - 品牌宣传支持者
  • 2026年重庆口碑好的古奥标识文旅景区标识设计公司推荐 - myqiye
  • 2026必备!降AIGC软件 千笔·降AI率助手 VS WPS AI,继续教育首选
  • 测完这批工具 8个AI论文平台测评:专科生毕业论文+开题报告高效写作指南
  • 基于电池二阶等效模型的SOC观测器设计
  • 详细介绍:ZooKeeper
  • 激关相关的模型,视频 增材制造.mph 激光焊接.mph run- 激光熔覆-可行.mph 激...
  • 不踩雷! 10个一键生成论文工具测评:专科生毕业论文+开题报告写作全攻略
  • 环保型精密轧机价格多少,靠谱供应商推荐 - 工业设备
  • 前方道路拥堵,但您仍在最优路线上
  • Nodejs+vue+ElementUI的教务选课考试成绩系统的设计与实现express-mysql
  • 说说靠谱的工业散热器源头厂家,哪家性价比高 - 工业品牌热点
  • 【保姆级教程】Claude Code 进阶指南:用 Everything Claude Code 打造更有“记忆”的 AI 程序员
  • 单片机仿真∶电流电压检测系统 可完成(1)电网参数监测,包括电流、电压。 (2)监测参数的显示
  • 2026年商用咖啡机厂家发布:以广东大正咖啡集团为代表的标杆企业深度解析 - 十大品牌推荐
  • 河北龙鹏注塑尼龙油壬价格贵吗,客户认可情况怎么样 - 工业推荐榜
  • 计算机教培 —— 如何写简历 —— 2026年入坑程序员请注意:千万别碰这几个即将被计算机行业淘汰的编程语言!Java/python/golang/C/C++/C#/开发/测试运维/后端/码士集团
  • 完整教程:Github/Gitee和Git实践