标签:java web
实例工程:
此图来自视频
新建java工程
将spring中的包导入。
新建接口IHelloMessage:
package com.jike.spring.ch01;
public interface IHelloMessage {
public String sayHello();
}实例化两个接口类:
HelloChina
package com.jike.spring.ch01;
public class HelloChina implements IHelloMessage {
@Override
public String sayHello() {
// TODO Auto-generated method stub
return "大家好";
}
}HelloWorld
package com.jike.spring.ch01;
public class HelloWorld implements IHelloMessage {
@Override
public String sayHello() {
// TODO Auto-generated method stub
return "Hello World";
}
}添加Person类:
package com.jike.spring.ch01;
public class Person {
private IHelloMessage helloMessage;
public IHelloMessage getHelloMessage() {
return helloMessage;
}
public void setHelloMessage(IHelloMessage helloMessage) {
this.helloMessage = helloMessage;
}
public String sayHello(){
return this.helloMessage.sayHello();
}
}加入主函数类:
package com.jike.spring.ch01;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Resource r = new FileSystemResource("helloMessage.xml");
BeanFactory f = new XmlBeanFactory(r);
Person person = (Person)f.getBean("person");
String s = person.sayHello();
System.out.println("The person is curretnly saying" + s);
}
}添加配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id = "helloWorld" class = "com.jike.spring.ch01.HelloWorld"></bean> <bean id = "helloChina" class = "com.jike.spring.ch01.HelloChina"></bean> <bean id = "person" class = "com.jike.spring.ch01.Person"> <property name="helloMessage" ref="helloWorld"></property> </bean> </beans>
运行。
注意,在lib中添加jar包,在http://commons.apache.org/proper/commons-logging/download_logging.cgi中下载
否则会出现
Exception in thread "main"java.lang.NoClassDefFoundError:
org/apache/commons/logging/LogFactory
的错误信息
极客学院:http://www.jikexueyuan.com/course/675_2.html?ss=1
标签:java web
原文地址:http://4440271.blog.51cto.com/4430271/1662206