通过构造函数注入属性基本和set方法注入类似,唯一不同的就是容器里面的标签不同
比如Demo类
package com.lihuia.ioc;
/**
* Copyright (C), lihuia.com
* FileName: Demo
* Author: lihui
* Date: 2018/7/28
*/
public class Demo {
private Girl girl;
public Demo() {}
public Demo(Girl girl) {
this.girl = girl;
}
public void sayHello() {
System.out.println("Hello, " + girl.myGirl());
}
}
这里通过构造函数传入girl,同时Girl类不变
package com.lihuia.ioc;
/**
* Copyright (C), lihuia.com
* FileName: Girl
* Author: lihui
* Date: 2018/7/28
*/
public class Girl {
public String myGirl() {
return "Lucy";
}
}
此时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="demo" class="com.lihuia.ioc.Demo">
<constructor-arg name="girl" ref="girl"></constructor-arg>
</bean>
<bean id="girl" class="com.lihuia.ioc.Girl"></bean>
</beans>
通过constructor-arg,从字面意思也可以看出来是构造函数的参数,单要注意的是:
(1)name表示的是构造函数里传入的参数,如果构造函数里传入girl1,name这里constructor-arg的name也必须是girl1,保持一致
(2)ref引用的是本XML里已经存在的Girl类型的bean
测试类没什么变化
package com.lihuia.ioc;
import javax.annotation.Resource;
import org.testng.annotations.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
/**
* Copyright (C), lihuia.com
* FileName: DemoTest
* Author: lihui
* Date: 2018/7/28
*/
@ContextConfiguration(locations = {"classpath:ioc.xml"})
public class DemoTest extends AbstractTestNGSpringContextTests {
@Resource(name = "demo")
private Demo demo;
@Test
public void testSayHello() {
demo.sayHello();
}
}
如果构造函数要传入多个参数,比如新增一个message,来传达要对girl说的话
package com.lihuia.ioc;
/**
* Copyright (C), lihuia.com
* FileName: Demo
* Author: lihui
* Date: 2018/7/28
*/
public class Demo {
private Girl girl;
private String message;
public Demo() {}
public Demo(Girl girl, String message) {
this.girl = girl;
this.message = message;
}
public void sayHello() {
System.out.println("Hello, " + girl.myGirl() + message);
}
}
此时girl的传入方式不变,只需要在XML里新增一个message的参数声明
<?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="demo" class="com.lihuia.ioc.Demo">
<constructor-arg name="girl" ref="girl"></constructor-arg>
<constructor-arg name="message" value=", Congratulations"></constructor-arg>
</bean>
<bean id="girl" class="com.lihuia.ioc.Girl"></bean>
</beans>
任意新增的参数都可以在demo bean里进行添加