我的第一个Spring程序

1、程序结构

我的第一个Spring程序

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 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();
} }

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"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 在容器文件中配置bean(service/dao/domain/action/数据源 -->
<!-- 配置bean和注入属性 -->
<!-- 相当于新建了一个userService对象,名称可随意,但是必须跟下面的<ref local="name">中的name相同 -->
<bean id="byeService3" class="com.service.ByeService">
<property name="name" value="涂富杰" />
</bean>
<bean id="userService" class="com.service.UserService">
<!-- 相当于调用了name的setName()方法 -->
<property name="name">
<value>tufujie</value>
</property>
<property name="byeService">
<ref local="byeService3" />
</property>
</bean>
</beans>

开发中出现错误:Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory

解决方案:加入commons-logging.jar这个架包即可。

上一篇:internet 协议入门


下一篇:Selenium简介(二)--基于CORE/IDE的简单应用