方式一:构造器注入【利用构造方法注入】
public class User {
private String name
;
private int age
;
private double money
;
public User(String name
, int age
, Double money
) {
this.name
= name
;
this.age
= age
;
this.price
= money
;
}
@Override
public String
toString() {
return "User{" +
"name='" + name
+ '\'' +
", age=" + age
+
", money=" + money
+
'}';
}
}
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.bean.User" >
<constructor-arg index="0" value="张三"/>
<constructor-arg name="age" value="18"/>
<constructor-arg type="java.lang.Double" value="23.5"/>
</bean>
</beans>
测试方法
@Test
public void test() {
ApplicationContext ca
= new ClassPathXmlApplicationContext("applicationContext.xml");
User user
= (User
) ca
.getBean("user");
System
.out
.println("user = " + user
);
}
注入成功!
转载请注明原文地址: https://yun.8miu.com/read-137099.html