一个Spring入门小案例

版权声明:本博客为记录本人学习过程而开,内容大多从网上学习与整理所得,若侵权请告知! https://blog.csdn.net/Fly_as_tadpole/article/details/83903263

创建两个类,配置类的bean对象。从容器取对象,调用方法。

Spring类

package com.southstar;

public class Spring {
    private String name;

    public void setBye(Bye bye) {
        this.bye = bye;
    }

    public Bye bye;

    public void setName(String name) {
        this.name = name;
    }
    public void sayHello(){
        System.out.println("hello:"+ name);
        bye.sayBye();
    }

Bye类

package com.southstar;

public class Bye {

    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public void sayBye()
    {
        System.out.println("bye:"+name);
    }
}

Test.java

package com.test;

import com.southstar.Spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class Test{

    public static void main(String[] arg)
    {
        ApplicationContext ac =new ClassPathXmlApplicationContext("Test.xml");
        Spring sp = (Spring)ac.getBean("spring");
        sp.sayHello();

    }
}

Test.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:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
	    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


<bean id="spring" class="com.southstar.Spring">
<property name="name">
    <value>没鱼</value>
</property>
    <property name="bye" ref="bye"/>

</bean>

    <bean id="bye" class="com.southstar.Bye">
        <property name="name" value="weib"></property>
    </bean>

</beans>

结果:

hello:没鱼
bye:weib

猜你喜欢

转载自blog.csdn.net/Fly_as_tadpole/article/details/83903263
今日推荐