spring helloworld

    初识spring,自然以helloword开始,spring将对象之间的关系交由spring配置文件管理,因此极大的减弱了对象间的耦合问题,想要say helloworld 当然少不了必要的工具:
    1.开发工具;
    2.jdk
    3.spring-framework 相关jar包
    如果上面的都准备好了,那么就开始吧!!
    首先:创建HelloMessage接口,创建HelloWorld类,因为我们要说helloword嘛!再写个HelloChina 类,在中国就要说中国话。
    第二:创建Person类,让Person来说!
    第三:创建helloworld.xml配置文件来规定各类间关系。
    第四:main方法读取配置文件,say HelloWorld
    是不是很简单?
    代码就这些:
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:aop="http://www.springframework.org/schema/aop"
    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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <bean id="helloWord" class="com.test.HelloWorld"></bean>
    <bean id="helloChina" class="E:\ompnew\springTest\src\com\test\HelloChina"></bean>
    <bean id="person" class="com.test.Person">
        <property  name="helloMesage" ref="helloWord"></property>
    </bean>
</beans>

person:

package com.test;
public class Person {
    private IHelloMessage helloMessage;
    public IHelloMessage getHelloMessage() {
        return helloMessage;
    }
    public void setHelloMessage(IHelloMessage helloMessage) {
        this.helloMessage = helloMessage;
    }
    public void sayHello(){
        System.out.println(helloMessage.sayMessage());
    }
}
hellomessage:
    package com.test;
    public interface IHelloMessage {
        public String sayMessage();
    }
helloworld:
    package com.test;
    public class HelloWorld implements IHelloMessage{
        @Override
        public String sayMessage() {
            // TODO Auto-generated method stub
            return "hello everyone !!!";
        }
    }
main:   
    package com.test;

    importorg.springframework.core.io.FileSystemResource;
    import org.springframework.core.io.Resource;
    importorg.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.*;
    public class Main {
        public static void main(String args[]){
            Resource res=new FileSystemResource("E:\\ompnew\\springTest\\src\\com\\test\\helloMessage.xml");
            BeanFactory bf=new XmlBeanFactory(res);
            Person p=(Person) bf.getBean("person");
            p.sayHello();
        }
    }
    好吧,代码就是这么简单,但此处注意,person的property与Person的属性对应,如若名称不同则会出下面错误:
     org.springframework.beans.NotWritablePropertyException: Invalid property 'helloMesage' of bean class [com.test.Person]: Bean property 'helloMesage' is not writable or has an invalid setter method. Did you mean 'helloMessage'?

猜你喜欢

转载自blog.csdn.net/lickybay/article/details/52839040
今日推荐