软件编程
位置:首页>> 软件编程>> java编程>> 基于Spring p标签和c标签注入方式

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

作者:迷惑的菜鸟  发布时间:2023-11-25 22:26:36 

标签:Spring,p标签,c标签,注入

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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com