应用场景:需要在Service中调用Dao的show方法
1.编写Service和Dao类
Dao类
package com.maty.property;
/**
* @author maty e-mail:512181558@qq.com
* @version 创建时间:2018年5月16日 下午3:37:12
* 类说明
*/
public class Dao
{
public void show()
{
System.out.println("Dao类中的show方法执行了");
}
}
Service类
package com.maty.property;import org.junit.Test;/** * @author maty e-mail:512181558@qq.com* @version 创建时间:2018年5月16日 下午3:36:57 * 类说明 */public class Service{ private Dao dao; //编写的set方法 public void setDao(Dao dao) { this.dao = dao; } //在Service类中引用Dao类中的show方法 @Test public void test() { dao.show(); }}
2.applicationContext.xml编写
<!-- 将Dao类注入到Spring中 -->
<bean id="dao" class="com.maty.property.Dao"></bean>
<!-- 将Service类注入到Spring -->
<bean id="service" class="com.maty.property.Service">
<!-- 将Dao注入到Service中
name属性值为需要被注入的Dao的实例名称
ref属性值为对应的bean的id值
-->
<property name="dao" ref="dao"></property>
</bean>
3.测试类的编写
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.maty.property.PropertyConstructor;
import com.maty.property.Service;
import com.maty.property.User;
/**
* @author maty e-mail:512181558@qq.com
* @version 创建时间:2018年5月16日 下午12:23:01
* 类说明
*/
public class MyTest
{
public static void main(String[] args)
{
//第一步:加载xml文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Service service = (Service) context.getBean("service");
service.test();
}
}
4.执行结果
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Dao类中的show方法执行了