spring基础应用(2)——依赖注入
依赖注入
当spring中一个对象A需要依赖另一个对象B的时候,我们需要在A里面引入一个B,同时需要给B注入一个对象,在这里我们先说的是手动装配,跟后面的自动装配autowired暂时没有关系。
通常手动装配一个对象我们有两种方法:
- 构造方法注入
- set方法注入
接下来我们依次来看,先看构造方法注入
构造方法注入
示例1:constructor-arg里面是ref
public class BeanOne {
public BeanOne(BeanTwo beanTwo){
}
}
<?xml version="1.0" encoding="UTF-8"?>
示例2:
当需要给基本数据类型和字符串注入的时候
public class ExampleBean {
// Number of years to calculate the Ultimate Answer
private final int years;
// The Answer to Life, the Universe, and Everything
private final String ultimateAnswer;
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
//可以用type和value
//可以用index和value
//也可以用name和value
set方法注入
示例1:给普通类里面的属性赋值
public class ExampleBean {
private AnotherBean beanOne;
private YetAnotherBean beanTwo;
private int i;
public void setBeanOne(AnotherBean beanOne) {
this.beanOne = beanOne;
}
public void setBeanTwo(YetAnotherBean beanTwo) {
this.beanTwo = beanTwo;
}
public void setIntegerProperty(int i) {
this.i = i;
}
}
示例2:给内部类里面的属性赋值
public class Outer {
private Person target;
public void setTarget(Person target) {
this.target = target;
}
public Person getTarget() {
return target;
}
static class Person{
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
}
示例3:为list、set、map、properties赋值
administrator@example.org
support@example.org
development@example.org
just some string
package com.ali.testspring;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class TestMap {
public List list1;
public Set set1;
public Map map1;
public Properties properties1;
public List getList1() {
return list1;
}
public void setList1(List list1) {
this.list1 = list1;
}
public Set getSet1() {
return set1;
}
public void setSet1(Set set1) {
this.set1 = set1;
}
public Map getMap1() {
return map1;
}
public void setMap1(Map map1) {
this.map1 = map1;
}
public Properties getProperties1() {
return properties1;
}
public void setProperties1(Properties properties1) {
this.properties1 = properties1;
}
}
package com.ali.testspring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
TestMap testMap=(TestMap)context.getBean("testMap");
System.out.println(testMap.getList1().size()); //2
System.out.println(testMap.getMap1().size()); //2
System.out.println(testMap.getProperties1().size()); //3
System.out.println(testMap.getSet1().size()); //2
}
}