Spring中基於construct(建構函式)的依賴注入
阿新 • • 發佈:2019-01-02
package com; public class User { private String name; private Integer age; private String country; public User(String name, Integer age, String country) { super(); this.name = name; this.age = age; this.country = country; } public String toString() { return name + " is " + age + " years old, living in " + country; } }
package com; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = (User)context.getBean("user"); System.out.println(user); } }
applicationContext.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="user" class="com.User" > <constructor-arg index="0" type="java.lang.String" value="Eswar" /> <constructor-arg index="1" type="java.lang.Integer" value="24"/> <constructor-arg index="2" type="java.lang.String" value="India"/> </bean> </beans>
輸出: Eswar is 24 years old, living in India