spring属性注入的set方法注入
生活随笔
收集整理的這篇文章主要介紹了
spring属性注入的set方法注入
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、值注入
創建我們要使用的User類:
在配置文件里配置:
<bean name="user" class="cn.it.bean.User"><property name="name" value="tom"></property><property name="age" value="18"></property></bean>寫一個測試類:
package cn.it.injection;import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.it.bean.User;public class Demo {@Testpublic void fun() {ApplicationContext ac = new ClassPathXmlApplicationContext("cn/it/injection/applicationContext.xml");User user = (User) ac.getBean("user");System.out.println(user);} }運行結果:
2、引用類型注入;
在編寫一個新的Car類:
將User類改成如下代碼:
package cn.it.bean;public class User {private String name;private int age;private Car car;public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}public User() {System.out.println("無參構造方法");}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "User [name=" + name + ", age=" + age + ", car=" + car + "]";}}在配置文件里配置如下:
<bean name="user" class="cn.it.bean.User"><property name="name" value="tom"></property><property name="age" value="18"></property><property name="car" ref="car"></property></bean><bean name="car" class="cn.it.bean.Car"><property name="name" value="寶馬"></property><property name="color" value="紅色"></property></bean>上面的測試類不用改變,直接運行,結果如下:
總結
以上是生活随笔為你收集整理的spring属性注入的set方法注入的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 白欣怡多少钱啊?
- 下一篇: 求两个数字的乘积,如果大于0,说明两个数