Spring传参数注解技术

Spring传参数注解技术,第1张

一、mybatis传多个参数(不使用@param注解情况和使用@param注解的情况)

转自 https://blog.csdn.net/qq_39505065/article/details/90550705

方法1:顺序传参法

1.不使用@param注解传递多个参数的情况

注: 使用jdk1.7得到的是: [1, 0, param1, param2]

使用1.8得到的则是: [arg1, arg0, param1, param2]

这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

举个栗子:

Dao层

List<User>demo(int userid, String name)

对应的XML编写

jdk1.7

<select id="demo" resultMap="User">

select *

from user where user_id=#{0} and name= #{1}

</select>

jdk1.8之后

第一种写法

<select id="demo" resultMap="User">

select *

from user where user_id=#{arg0} and name= #{arg1}

</select>

第二种写法

<select id="demo" resultMap="User">

select *

from user where user_id=#{param0} and name= #{param1}

</select>

方法2:@Param注解传参法

public User selectUser(@Param("userName") String name, int @Param("deptId") deptId)

<select id="selectUser" resultMap="UserResultMap">

select * from user

where user_name = #{userName} and dept_id = #{deptId}

</select>

这种方法在参数不多的情况还是比较直观的,推荐使用。

方法3:Map传参法

public User selectUser(Map<String, Object>params)

<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">

select * from user

where user_name = #{userName} and dept_id = #{deptId}

</select>

这种方法适合传递多个参数,且参数易变能灵活传递的情况。

方法4:Java Bean传参法

public User selectUser(Map<String, Object>params)

<select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">

select * from user

where user_name = #{userName} and dept_id = #{deptId}

</select>

这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。

二、《Spring @RequestParam注解的使用》

https://blog.csdn.net/Third_Week/article/details/90376578

ClassPathXmlApplicationContext使用方法:(classpath路劲查找)

ClassPathXmlApplicationContext 默认会去 classPath 路径下找。classPath 路径指的就是编译后的 classes 目录。

FileSystemXmlApplicationContext使用方法(项目路径或者相对路径)

FileSystemXmlApplicationContext 默认是去项目的路径下加载,可以是相对路径,也可以是绝对路径,若是绝对路径,“file:” 前缀可以缺省。

构造注入三种方式标明方法中的参数:

1.type 根据数据类型

2.index 根据顺序

3.name 根据参数名

仍保留集合了特性。

autowire属性设置自动组装参数

@Component:表明该类会作为组件 类,并告知Spring要 为这个类创建bean。

@ComponentScan:启用组件扫描, 默认当前配置类 所在包为基础包。

basePackages : 基础包 basePackageClasses: 指定类所在包为基础包

@Primary:(一 般与@Component 配合使用)在自动装配时,设置 某个bean为首选。

@Autowired:自动注入一个符 合类型要求的 bean

required: 是否为必须注入项。

@Qualifier:指定所注入的 bean的ID

value: 所注入的bean的ID

@Scope:定义bean的作用域。

@Configuration:定义Spring配置类

@Bean:声明配置该方法所 产生的对象为 Spring中的bean

@Import:导入其他配置类

@ImportResouce:导入其他XML配置文件


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11765287.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-18
下一篇2023-05-18

发表评论

登录后才能评论

评论列表(0条)

    保存