一、 定义GreetingService接口
package cn.csdn.hr.service;
publicinterface GreetingService {
publicvoid sayGeeting();
}
二、 定义GreetingServiceImpl类并实现GreetingService接口
package cn.csdn.hr.service;
publicclass GeetingServiceImplimplements GreetingService {
private String greeting;
/*bean配置文件中property属性name 的名称和greeting一致,自动通过set方法注入*/
//依赖注入
publicvoid setGreeting(String greeting) {
this.greeting = greeting;
}
publicvoid sayGeeting() {
System.out.println(greeting);
}
}
三、 定义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-2.5.xsd">
<bean id="greetingServiceBean" class="cn.csdn.hr.service.GeetingServiceImpl" scope="singleton">
<!-- propertybean中的属性值 -->
<property name="greeting">
<value>你好!</value>
</property>
</bean>
</beans>
四、 测试
package cn.csdn.hr.junit;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import cn.csdn.hr.service.GeetingServiceBean;
import cn.csdn.hr.service.GreetingService;
public class AppMain {
@Test
public void test() {
//装配bean
ApplicationContext context=new FileSystemXmlApplicationContext("D:\\Users\\Administrator\\workspace\\day\\src\\applicationContext.xml");
//创建beanFacory工厂
//获取BeanFactory工厂创建的bean对象
GreetingService greetingService =(GreetingService) context.getBean("greetingServiceBean");//xml资源文件中的classbean
//使用bean的实例
greetingService.sayGeeting();
}
@Test
public void test1() {
//装配bean
//创建依赖的资源文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取BeanFactory工厂创建的bean对象
GreetingService greetingService =(GreetingService)applicationContext.getBean("greetingServiceBean");//xml资源文件中的classbean的id名称
//使用bean的实例
greetingService.sayGeeting();
}
}