當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
2.2 Spring属性注入-构造方法
生活随笔
收集整理的這篇文章主要介紹了
2.2 Spring属性注入-构造方法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
代碼:
spring2.2-構(gòu)造方法注入.zip - 藍(lán)奏云文件大小:14.9 K|https://www.lanzouw.com/iLbBBvpug4b
1、定義Category和Product類,定義有參構(gòu)造函數(shù),
package com.how2j.pojo;public class Category {private int id;private String name;//定義無參構(gòu)造函數(shù),如果提供了Set方法,則可以使用Set方法注入屬性public Category() {}//定義有參構(gòu)造函數(shù),可以使用構(gòu)造方法來注入屬性public Category(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}@Overridepublic String toString() {return "Category{" +"id=" + id +", name='" + name + '\'' +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;} } package com.how2j.pojo;public class Product {//普通屬于類型private int id;private String name;//引用類型private Category category;public Product() {}public Product(int id, String name, Category category) {this.id = id;this.name = name;this.category = category;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Category getCategory() {return category;}public void setCategory(Category category) {this.category = category;}@Overridepublic String toString() {return "Product{" +"id=" + id +", name='" + name + '\'' +", category=" + category +'}';} }2、編寫xml文件,
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"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"><bean id="c" class="com.how2j.pojo.Category"><constructor-arg name="id" value="1"/><constructor-arg name="name" value="category 1"/></bean><bean id="p" class="com.how2j.pojo.Product"> <!-- 普通屬性--><constructor-arg name="id" value="1"/><constructor-arg name="name" value="product 1"/> <!-- 引用屬性--><constructor-arg name="category" ref="c"/></bean> </beans>3、測試
package test;import com.how2j.pojo.Category; import com.how2j.pojo.Product; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestSpring {@Test//spring的控制翻轉(zhuǎn)public void test1(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );Category c = (Category) context.getBean("c");System.out.println(c);}@Test//測試spring的屬性注入public void test2(){ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml" );Product p = (Product) context.getBean("p");System.out.println(p);} }補(bǔ)充:目錄結(jié)構(gòu)如下:
總結(jié)
以上是生活随笔為你收集整理的2.2 Spring属性注入-构造方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2.1、spring属性注入-Set方法
- 下一篇: 3、Spring配置类