使用构造方法注入
目录结构
TestDiDao
package dao;
public interface TestDiDao {
public void sayHello();
}
TestDiDaoImpl
package dao;
public class TestDiDaoImpl implements TestDiDao{
@Override
public void sayHello() {
System.out.println("TestDiDao say: Hello, Study hard!");
}
}
TestDiService
package service;
public interface TestDiService {
public void sayHello();
}
TestDiServiceImpl
package service;
import dao.TestDiDao;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
public class TestDiServiceImpl implements TestDiService{
private final TestDiDao testDiDao;
public TestDiServiceImpl(TestDiDao testDiDao){
super();
this.testDiDao = testDiDao;
}
@Override
public void sayHello() {
testDiDao.sayHello();
System.out.println("TestDiService 构造方法注入 say: Hello, Study hard!");
}
}
TestDi
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.TestDiService;
public class TestDi {
public static void main(String[] args){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
TestDiService testDiService = (TestDiService) applicationContext.getBean("testDiService");
testDiService.sayHello();
}
}
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">
<!--将指定类TestDiDaoImpl配置给Spring,让Spring创建其实例-->
<bean id="myTestDiDao" class="dao.TestDiDaoImpl">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!--使用构造方法注入-->
<bean id="testDiService" class="service.TestDiServiceImpl">
<!--将myTestDiDao注入到TestDiServiceImpl类的属性testDiDao上-->
<constructor-arg index="0" ref="myTestDiDao"/>
<!--在配置文件中,constructor-arg元素用于定义类构造方法的参数,index用于定义参数的位置,
ref指定某个实例的引用,如果参数是常量值,ref由value代替,如:
<constructor-arg index="1" value="41890"/>-->
</bean>
</beans>