美文网首页
spring工程的创建

spring工程的创建

作者: vanhukset | 来源:发表于2017-11-05 15:49 被阅读0次

建立 spring的工程
编写java类
配置文件

step one

新建一个普通的java的项目

image.png

载入java包

新建lib文件夹

image.png

复制进入java包
把lib加入到java build path中

image.png

新增class IHelloMessage

//HelloSpring/src/com/jike/spring/chapter01/IHelloMessage .java
package com.jike.spring.chapter01;

public interface IHelloMessage {
    public String sayHello();
}

编写helloworld hellochina两个类实现该接口

//HelloSpring/src/com/jike/spring/chapter01/HelloWorld .java
package com.jike.spring.chapter01;

public class HelloWorld implements IHelloMessage {

    @Override
    public String sayHello() {
        // TODO Auto-generated method stub
        return "Hello World";
    }

}

//path  HelloSpring/src/com/jike/spring/chapter01/HelloChina .java
package com.jike.spring.chapter01;

public class HelloChina implements IHelloMessage {

    @Override
    public String sayHello() {
        // TODO Auto-generated method stub
        return "大家好";
    }

}


项目目录下面新建helloMessage.xml

///HelloSpring/helloMessage.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 id="helloWorld" class="com.jike.spring.chapter01.HelloWorld"></bean>
    <bean id="helloChina" class="com.jike.spring.chapter01.HelloChina"></bean>
    <bean id="person" class="com.jike.spring.chapter01.Person">
        <property name="helloMessage" ref="helloChina"/>
    </bean>
</beans>

编写Main.java

package com.jike.spring.chapter01;
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
        //利用FileSystemResource读取配置文件
        Resource r = new FileSystemResource("helloMessage.xml");
        //利用XmlBeanFactory来加载配置文件,启动IOC容器
        BeanFactory f = new XmlBeanFactory(r);
        //从IOC容器中获取Person类的实例
        Person person = (Person) f.getBean("person");
        //person实例向大家输出问候信息
        String s = person.sayHello();
        //在系统控制台中打印问候信息,由于在这里配置文件中配置是HelloWorld的实例,
        //所以,在这里打印的是字符串:HelloWorld
        System.out.println("The Person is currently saying: "+s);
    }

}


运行main.java。执行成功

相关文章

网友评论

      本文标题:spring工程的创建

      本文链接:https://www.haomeiwen.com/subject/zdacmxtx.html