在Spring中注入方式有设置注入和构造注入。设置注入就是指要被注入的类中定义有一个setter()方法,并在参数中定义需要注入的对象。简单的看个例子。
定义有User类,并覆写了toString()方法。
package com.zcl.spring.setterinjection; public class User { private String name ; private int age ; private String country ; 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; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String toString(){ return name + " is " + age + " years old,living in " + country ; } }
配置beans.xml文件,通过设置注入为类中属性注入值
<?xml version="1.0" encoding="UTF-8"?> <beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"> <bean id="user" class="com.zcl.spring.setterinjection.User"> <property name="name" value="Zhao" /> <property name="age" value="22" /> <property name="country" value="China" /> </bean> </beans>
测试一下:
package com.zcl.spring.setterinjection; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String args[]){ ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml") ; User user = (User)context.getBean("user") ; System.out.println(user) ; } }
输入结果:
Zhao is 22 years old,living in China
现在我们来看写构造注入,所谓构造注入就是指要被注入的类中声明一个构造方法,并在此方法的参数中定义要注入的对象。修改下刚刚的User类。
package com.zcl.spring.setterinjection; public class User { private String name ; private int age ; private String country ; public User(String name, int age, String country) { this.name = name; this.age = age; this.country = country; } public String toString(){ return name + " is " + age + " years old,living in " + country ; } }
配置beans.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"> <bean id="user" class="com.zcl.spring.setterinjection.User"> <constructor-arg value="Zhao" /> <constructor-arg value="22" /> <constructor-arg value="China" /> </bean> </beans>
测试函数一样,打印结果也一样。