在spring第三篇中介绍了bean元素属性 在第四篇中介绍spring注入的方式
1 set方法注入
建立一个User类 创建私有的属性 set get 方法 重写toString方法 代码如下:
package bean;
public class User {
private String name;
private int age;
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;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
书写配置文件 代码如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<bean name="user" class="bean.User">
<property name="name" value="lijun"></property>
<property name="age" value="39"></property>
</bean>
</beans>
测试代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<bean name="user" class="bean.User">
<property name="name" value="lijun"></property>
<property name="age" value="39"></property>
</bean>
</beans>
测试结果如下图
2 构造函数注入
在User类里面添加有参构造函数 代码是:
public User(String name,int age){
System.out.println("这是string");
this.name=name;
this.age = age;
}
配置文件写成如下人代码:
<bean name="user1" class="bean.User">
<constructor-arg name="name" value="lijun"></constructor-arg>
<constructor-arg name="age" value="39"></constructor-arg>
</bean>
constructor-arg是构造函数注入的关键词,
测试代码如下
@Test
public void func2(){
ApplicationContext ac = new ClassPathXmlApplicationContext("com/lijun/demo/applicationContext.xml");
User u = (User)ac.getBean("user1");
System.out.println(u);
}
因为参数一样 所以测试结果会跟上次set测试结果一样。
原文地址:https://www.cnblogs.com/lijun6/p/10345405.html