springHelloWorld

本教程详细介绍了Spring框架的入门级项目搭建过程,包括环境配置、项目创建、依赖库添加及核心HelloWorld应用实现。通过创建Java项目,添加Spring必要组件如spring-aop、spring-context等,并构建HelloWorld实例,演示了如何利用Spring Context API加载配置文件,获取并展示bean实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springHelloWorld

入门第一个项目,在此之前完成了,spring环境的搭建,该项目的内容是输出helloworld

  1. 创建java项目
  2. 给项目添加必要的库(XXX-5.1.9RELEASE.jar)
spring-aop,
spring-aspects,
spring-beans,
spring-context,
spring-context-indexer,----
spring-context-support,
spring-core,
spring-expression,
spring-instrument,
spring-jcl,------------4.1.6中叫做spring-instrument
spring-jdbc,
spring-jms,
spring-messaging,
spring-orm,
spring-oxm,
spring-test,
spring-tx,
spring-web,
spring-webflux,--4.1.6中 spring-webmvc-portlet
spring-webmvc,
spring-websocket,


commands-logging-1.2.jar

注:我学习参照的教程spring版本是4.1.6,而此时我的版本是5.1.9,里面的少部分包有了变化,学习时尤其要注意。

从4.1.6-》5.1.9版本有变化的地方:少了spring-jcl包,,增加了spring-instrument包,少了spring-webmvc-portlet,增加了spring-webflux包

  1. 创建源文件

    • 建立源文件 HelloWorld.javaMainApp.java
    package com.tutorialspoint;
    public class HelloWorld {
    	private String message;
    
    	public String getMessage() {
    		return message;
    	}
    
    	public void setMessage(String message) {
    		this.message = message;
    	}
    	
    }
    
    
    package com.tutorialspoint;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MainApp {
    	public static void main(String[] arg) {
    
            //框架 API ClassPathXmlApplicationContext() 来创建应用程序的上下文
    		ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    		
            //使用已创建的上下文的 getBean() 方法来获得所需的 bean,这个方法使用 bean 的 ID 返回一个最终可以转换为实际对象的通用对象
    		HelloWorld obj = (HelloWorld)context.getBean("helloWorld");
    		System.out.println(obj.getMessage());
    		
    	}
    }
    
  2. 创建bean的配置文件

    • 在src下,建立beans配置文件

      <?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
              https://www.springframework.org/schema/beans/spring-beans.xsd">
      
          <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">   
          
          	<property name="message" value="Hello world!"></property>
          
          </bean>
      
      </beans>
      
      

      注意:bean 的写法可以去参考spring下的的schema\beans\spring-beans.xsd,读官方的文档,头部的信息可以直接在官方给的参考示例中复制,然后在添加本项目的配置

      官方的参考文档core.html的1.2.1里面有配置文件的参考示例

  3. 运行

参考

参考的是w3cshool的spring教程 https://www.w3cschool.cn/wkspring/dgte1ica.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值