自己总结下 比较浅的 理解 适合 初学者:
1.构造方法 注入
直接上代码
<!-- 构造方法注入 -->
<bean id="testservice" class="com.javen.service.impl.ITestServiceImpl">
<constructor-arg ref="testDaoImpl"></constructor-arg>
</bean>
<bean id ="testDaoImpl" class="com.javen.dao.testDaoImpl"/>
先在spring配置文件中,一个bean class指向你个对象 的路径,就比如上面的testDaoImpl。在写个bean对象,指向service的对象路径, 在bean加 <constructor-arg/> 属性 。 <constructor-arg/>的意思就是通过构造函数注入。
public class ITestServiceImpl implements TestService{
private testDao testDaoImpl;
public ITestServiceImpl(testDao testDaoImpl) {
this.testDaoImpl = testDaoImpl;
}
public static void main(String[] args) {
ClassPathXmlApplicationContext cx = new ClassPathXmlApplicationContext("spring-mybatis.xml");
ITestServiceImpl service = (ITestServiceImpl) cx.getBean("testservice");
service.testDS();
}
@Override
public void testDS() {
testDaoImpl.doTest();
}
}
在ITestServiceImpl 通过构造方法注入testDao,为能够访问Dao的方法 如上面代码, 在service实现类中加一个属性。(属性名要和 你在配置文件bean里的属性constructor-arg的ref 保持一致)。 然后在service 类中写个有参数的构造函数。这样就注入Dao ,在service里就可以访问Dao的方法。 我这里Dao的方法就是一条打印语句。测试成功 说明Dao成功注入了service类中
2.set get 注入方法
<!-- set get方法注入 -->
<bean id="testservice" class="com.javen.service.impl.ITestServiceImpl">
<property name="testDaoImpl" ref="testDaoImpl"></property>
</bean>
<bean id ="testDaoImpl" class="com.javen.dao.testDaoImpl"/>
和构造注入异曲同工之妙。
private testDao testDaoImpl;
public testDao getTestDaoImpl() {
return testDaoImpl;
}
public void setTestDaoImpl(testDao testDaoImpl) {
this.testDaoImpl = testDaoImpl;
}
3. 使用spring的注解来注入
在要注入的Dao 的属性上 加 @Autowired。
就先这样吧!!!!!!