1.主函数:
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.service.ByeService;
import com.service.UserService;
import com.util.ApplicationContextUtil;
import com.util.*;
public class Test {
public static void main(String[] args) {
//1.得到spring的applicationContext对象(容器对象)
//这个applicationContext对象其实就是对应的applicationContext.xml这个文件
//而这个文件中配置的有bean,将来通过这个对象就能取出这个东西了
//容器特性,注入bean 配置属性
//在这里就将数据注入进bean
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)ac.getBean("userService");//获取到实例对象
userService.sayHello();
}
}
ByeService 类:
package com.service;
public class ByeService {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayBye() {
System.out.println("bye" + name);
}
}
UserService 类:
这里UserService类引用了ByeService类,并将它的get和set方法进行了设定,但是如果没有在.xml文件中使用ref引用,那么就会导致无法实例化BysService,从此无法调用其中的方法。
package com.service;
public class UserService {
private String name;
private ByeService byeService;
public ByeService getByeService() {
return byeService;
}
public void setByeService(ByeService byeService) {
this.byeService = byeService;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("hello" + name);
byeService.sayBye();
}
}
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 在容器文件中配置bean(service/dao/domin/action/数据源) -->
<!-- spring在加载的时候,就会去看这里是不是有bean,如果有bean的话就开始实例化这个bean,并装载到内存中
UserService userService = new UserService();
userService.setName("ok");
上面两句话电脑怎么办到的呢?
利用反射机制:读了这个class文件,加载这个id的实体,通过这个属性的set方法进行实现,
那么在UserService.java文件中的set方法必须写,不然值无法注入进去。
-->
<bean id = "userService" class = "com.service.UserService">
<property name="name">
<value>
OK
</value>
<!--
在userService中引用 byeService bean
-->
</property>
<!-- ref代表我引用了spring容器中配置的bean -->
<property name="byeService" ref="byeService"></property>
</bean>
<bean id="byeService" class="com.service.ByeService">
<property name="name">
<value>小明</value>
</property>
</bean>
</beans>
输出结果:
hello OK
bye小明