服务器之家

服务器之家 > 正文

基于Spring p标签和c标签注入方式

时间:2022-01-19 00:53     来源/作者:迷惑的菜鸟

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> 元素

基于Spring p标签和c标签注入方式

基于Spring p标签和c标签注入方式

可以index|name|type 三选一 、三选二 ; ref|value 二选一

2.setter方法注入(开发推荐)

基于Spring p标签和c标签注入方式

为需要注入属性提供setter方法

配置 每个注入属性, 对应<property> 元素

基于Spring p标签和c标签注入方式

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. 简化注入的配置

基于Spring p标签和c标签注入方式

4.集合类型的属性注入(了解)

Spring 对每个常用集合对象,提供单独元素完成注入

  • List 对象 ---- <list> 元素
  • Set 对象 ---- <set> 元素
  • Map对象 ----<map>元素
  • Properties 对象 ---- <props> 元素

基于Spring p标签和c标签注入方式

集合属性的注入,主要用于框架的配置 !

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/weixin_46608377/article/details/114322157

相关文章

热门资讯

蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部