欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

Spring中的常用注解

发布时间:2025/3/19 javascript 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Spring中的常用注解 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1 第一步导包


首先需要导入这四个包以及日志文件(slf4j-log4j12-1.7.5.jar)

2 配置xml文件

<--配置文件信息--> <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"><!-- 开启注解功能 --><context:annotation-config/><!-- 开启注解扫描功能,该包下所有的@Component <context:component-scan base-package="com.hisoft"/><!--<context:componet-scan> 具有 <context:annotation-config> 作用 ! 所以第一步开启注解功能也可以省略-->

配置本地提示:

3 常用注解

- @Component 这种注解可以在dao层或者service层等都可以使用,没有限制,有三种使用方式

@Component //默认id为类名首字母变小写@Component(value="usermapper") //设置id名称@Component("usermapper")//设置id名称

实际开发中,使用的是@Component三个衍生注解(“子注解”)
子注解的作用:有分层的意义(分层注解)。

- 简单数据类型依赖注入

@Value("张三")//直接给属性注入值String name;@Value("123")String password;其实这种方式是等价于 String name = "张三";

- 复杂类型数据依赖注入

第一种: 使用@Value 结合SpEL #{} ---- spring3.0 后用 Service层注入dao层

dao层@Component("usermapper") service层@Value("#{usermapper}")UserMapperImpl usermapper;

第二种:使用@Autowired 或者结合 @Qualifier

单独使用@Autowired 按照类型注入


使用@Autowired + @ Qualifier 按照名称注入

第三种: JSR-250标准(jdk) 提供@Resource

第四种: JSR-330标准(jdk) 提供 @Inject (麻烦点)不推荐(了解)
需要先导入 javax.inject 的 jar (废掉了)
按照类型注入

按照名称注入

汇总

总结

以上是生活随笔为你收集整理的Spring中的常用注解的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。