spring setter注入
第一步: 编写实体类
Dog.java
package com.xuzhiwen.spring7; public class Dog { private String name; private String hobby; public void setName(String name) { this.name = name; } public void setHobby(String hobby) { this.hobby = hobby; } @Override public String toString() { return "Dog [name=" + name + ", hobby=" + hobby + "]"; } }
第二步:编写配置文件
applicationContext6.xml
<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-3.0.xsd"> <bean id="dog" class="com.xuzhiwen.spring7.Dog"> <property name="name" value="dahuang" /> <property name="hobby" value="eat food" /> </bean> </beans>
第三步:编写测试类
package com.xuzhiwen.spring7; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext6.xml"); Dog dog = (Dog) app.getBean("dog"); System.out.println(dog); } }
第四步:运行结果如下