【wyy】springIOC之属性注入

来源:互联网 发布:未婚先孕妈妈知乎 编辑:程序博客网 时间:2024/06/14 09:24

1.创建一个student类

package com.baidu.ioc;public class Student {private String name;private Integer age;private String sex;/*public Student(String name, Integer age, String sex) {super();this.name = name;this.age = age;this.sex = sex;}*/public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}
2.application.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"       xmlns:p="http://www.springframework.org/schema/p"      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">        <bean id="student" class="com.baidu.ioc.Student">    <property name="name" value="王阳阳"/>    <property name="age" value="26"/>    <property name="sex" value="男"/>    <!-- <property name="name">    <value>王阳阳</value>    </property>    <property name="age">    <value>26</value>    </property>    <property name="sex">    <value>男</value>    </property> -->    </bean></beans>

3.创建一个student的测试类

package com.baidu.ioc;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestStudent {public static void main(String[] args) {/** * set注入构造器注入 */ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");Student stu = (Student) applicationContext.getBean("student");System.out.println(stu.getName()+stu.getSex()+stu.getAge());}}



注:两个标红的student名称要一致,大小写敏感!

原创粉丝点击