基于Spring p标签和c标签注入方式
时间:2022-04-19 08:30:08|栏目:JAVA代码|点击: 次
Spring p和c标签注入方式
1.编写实体类
package com.ming04.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
}
2.配置文件(重点)
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- p命名空间注入 ,可以直接注入属性的值 :property -->
<bean id="user" class="com.ming04.pojo.User" p:name="秦小东" p:id="18"/>
<!-- c命名空间注入 可以构造器注入属性的值 :construct-args -->
<bean id="user2" class="com.qin.pojo.User" c:id="19" c:name="狂神" />
</beans>
3.测试
@Test
public void Text(){
ApplicationContext context = new ClassPathXmlApplicationContext("Beans04.xml");
User user = (User) context.getBean("user2");
System.out.println(user);
}
spring Bean注入和P标签使用
1.构造方法参数
对应 配置文件 <constructor-arg> 元素


可以index|name|type 三选一 、三选二 ; ref|value 二选一
2.setter方法注入(开发推荐)

为需要注入属性提供setter方法
配置 每个注入属性, 对应<property> 元素

3.p名称空间的使用
spring2.5以后,为了简化setter方法属性注入,引用p名称空间的概念,可以将<property> 子元素,简化为<bean>元素属性配置 !!
a.
在applicationContext.xml 引入p 名称空间
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
b. 简化注入的配置

4.集合类型的属性注入(了解)
Spring 对每个常用集合对象,提供单独元素完成注入
- List 对象 ---- <list> 元素
- Set 对象 ---- <set> 元素
- Map对象 ----<map>元素
- Properties 对象 ---- <props> 元素

集合属性的注入,主要用于框架的配置 !
上一篇:解决SpringCloud Gateway配置自定义路由404的坑
栏 目:JAVA代码
下一篇:Java的Spring框架中bean的继承与内部bean的注入
本文标题:基于Spring p标签和c标签注入方式
本文地址:http://www.codeinn.net/misctech/199616.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




