spring02 搭建spring环境

1. 添加jar包

 Commons-logging 是spring必须依赖的一个日志包。

    <?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="

        http://www.springframework.org/schema/beans    

        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

        http://www.springframework.org/schema/context

        http://www.springframework.org/schema/context/spring-context-3.0.xsd">   

       

    <bean id="helloWork" class="com.atguigu.beans.Hellowork">

    <property name ="name" value="springg"></property>

     注意: name=“name”的值 需要和实体类中set方法对应。不然会出错。

    </bean>

</beans>

package com.atguigu.beans;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class Main {

 

    public static void main(String[] args) {

        //Hellowork hellwork = new Hellowork();

        //hellwork.setName("bigzq");

        //hellwork.hello();

//注意: 在执行下一步操作的时候,spring容器为我们创建这个类的实例,并进行初始化,根据配置文件进行赋值。

        ApplicationContext axt  = new ClassPathXmlApplicationContext("applicationContext.xml");

       

Hellowork hellwork = (Hellowork) axt.getBean("helloWork");

        hellwork.hello();

    }

}

package com.atguigu.beans;

 

public class Hellowork {

 

    private String name;

    private String sayHello;

   

    public void setName(String name){

        this.name=name;

        System.out.println("name ==="+name);

    }

   

    public void hello(){

        System.out.println("hello ==="+ name);

    }

 

    public Hellowork() {

       

        System.out.println("构造方法执行");

    }

 

    public String getSayHello() {

        return sayHello;

    }

 

    public void setSayHello(String sayHello) {

        this.sayHello = sayHello;

        System.out.println("sayHello===="+sayHello);

    }

 

    public String getName() {

        return name;

    }

   

   

}

 

  

输出结果:  我们用ClassPathXmlApplicationContext 来加载我们配置的xml 得到上下文:ApplicationContext,这个时候调用他的hello方法,我们没有显示赋值,但是控制台会打印

我们在applicationContext.xml已经给它赋值了。

 

posted on 2017-11-16 15:23  大志强  阅读(121)  评论(0)    收藏  举报