1、程序结构
2、各个文件
ByeService.java
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.java
package com.service;
public class UserService {
private String name;
private ByeService byeService2;
public ByeService getByeService2() {
return byeService2;
}
public void setByeService2(ByeService byeService2) {
this.byeService2 = byeService2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("hello " + name);
byeService2.sayBye();
}
}
Test.java
package com.test;
import com.service.UserService;
import com.util.ApplicationContextUtil;
public class Test {
public static void main(String[] args) {
((UserService) ApplicationContextUtil.getApplicationContext().getBean(
"userService")).sayHello();
}
}
ApplicationContextUtil.java
package com.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
final public class ApplicationContextUtil {
private static ApplicationContext ac = null;
private ApplicationContextUtil() {
}
static {
ac = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static ApplicationContext getApplicationContext() {
return ac;
}
}
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:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- 在容器文件中配置bean(service/dao/domain/action/数据源 -->
<!-- 配置bean和注入属性 -->
<!-- 相当于新建了一个userService对象 -->
<bean id="userService" class="com.service.UserService">
<!-- 相当于调用了name的setName()方法 -->
<property name="name">
<value>涂富杰</value>
</property>
<property name="byeService2" ref="byeService"></property>
</bean>
<bean id="byeService" class="com.service.ByeService">
<property name="name" value="小杰" />
</bean>
</beans>
原文:http://www.cnblogs.com/tufujie/p/4915969.html