⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hello.java.txt

📁 就我们的第一个Spring程序
💻 TXT
字号:
package onlyfun.caterpillar;

public class HelloBean {
    private String helloWord = "Hello!World!";
   
    public void setHelloWord(String helloWord) {
        this.helloWord = helloWord;
    }
    public String getHelloWord() {
        return helloWord;
    }
}
HelloBean有预设的"Hello!World!"字符串,我们也可以透过setter来设定新的招呼语,不过我们不亲自撰写程序来作这些事,而是在组态档案定义,由Spring来为我们作设定的动作,我们撰写bean.xml: 

bean.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="helloBean" class="onlyfun.caterpillar.HelloBean">
        <property name="helloWord"><value>Hello!Justin!</value></property>
    </bean>
</beans>

 bean.xml中定义了JavaBean的别名与来源类别,<property>标签中设定了我们希望注入至JavaBean的字符串值,bean.xml必须在您的CLASSPATH可以存取到的目录中,也许是现行的工作目录,在Web程序中可以是在classes目录下,我们这边使用的是单机程序的方式,将使用FileInputStream读取bean.xml,所以将之置于现行的工作目录中,接着我们撰写一个简单的测试程序:

SpringTest.java

package onlyfun.caterpillar;

import java.io.*;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

public class SpringTest {
    public static void main(String[] args) throws IOException {
        InputStream is = new FileInputStream("bean.xml");
        BeanFactory factory = new XmlBeanFactory(is);
       
        HelloBean hello = (HelloBean) factory.getBean("helloBean");
        System.out.println(hello.getHelloWord());
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -