方式一:构造器注入【利用构造方法注入】
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;
}
//重写toString方法
@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" >
<!--
要赋的值: name=张三 age=12 money=20
index:根据索引选择属性
type:根据属性数据类型选择属性
name:根据属性名选择属性
ref:注入复杂属性值【例如注入一个对象】
value:要给属性赋的值
-->
<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");
//通过id从工厂获取Bean
User user = (User) ca.getBean("user");
System.out.println("user = " + user);
}
注入成功!