spring学习2(环境搭建)

spring第一个程序HelloWorld

1新建java项目
2导入一下jar
image.png
3新建HelloWorld
package chen;
public class HelloWorld {
    private String name;
    public void hello() {
        System.out.print(name);
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

4配置bean.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="hello" class="chen.HelloWorld">
        <property name="name" value="你好 Spring"></property>
    </bean>
</beans>

5程序入口
package chen;

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

public class Main {
public static void main(String[] args) {
    
        // 1.创建ioc容器对象
        //ApplicationContext代表ioc容器
        //ClassPathXmlApplicationContext:是ApplicationContext的实现类 从类路径下加载配置文件
        ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
        
        // 2.从ioc容器中获取bean实例
        //利用id获取实例
        //HelloWorld hWorld = (HelloWorld) ctx.getBean("hello");
        //利用类型获取实例 但类型唯一
        HelloWorld hWorld =  ctx.getBean(HelloWorld.class);
        
        // 3.调用方法
        hWorld.hello();
}

}

项目结构如下:


image.png

我们的第一个spring 程序就完成了

  • ApplicationContext代表ioc容器
  • ClassPathXmlApplicationContext:是ApplicationContext的实现类 从类路径下加载配置文件

总结:

  • 配置spring bean配置文件
  • 创建ioc容器对象
  • 从ioc容器中获取bean实例
  • 调用方法
    下一篇 spring学习3
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,286评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,010评论 6 342
  • Spring容器高层视图 Spring 启动时读取应用程序提供的Bean配置信息,并在Spring容器中生成一份相...
    Theriseof阅读 2,871评论 1 24
  • 是谁碰乱了时光 是谁叫醒了梦想 风雪袭来 将细雨隐藏 我和夕阳 对望 微笑 念念不忘 谁说的胜者为王 谁写的地老...
    亦是人海孤鸿阅读 406评论 1 3
  • 追求完美是好的,因为有了期待与动力,用在工业生产上非常合适,因为机器是死物,它不会有抱怨与指责。可孩子不同,...
    缺心璞玉阅读 858评论 0 2