使用Maven构建Spring项目“HelloWorld”

傷城~ 2022-06-13 04:36 381阅读 0赞

开始学习Spring,因为以前都没用过Maven,所以打算边学习Spring边熟悉Maven。这里自己使用Maven构建一个spring项目demo

1、新建maven项目:
新建maven项目

新建maven项目

2、构建Spring环境:
打开maven项目根目录中的pom.xml,点击dependencies添加add:

  • groupId: org.springframework
  • artifactId: spring-context
  • version: 4.3.9.RELEASE

enter image description here

保存pom.xml后如果显示下图说明Spring环境搭建成功了:
enter image description here

3、创建bean类

  1. package com.gisxx.springTest;
  2. public class TestBean {
  3. private String name;
  4. public TestBean() {
  5. }
  6. public TestBean(String name) {
  7. super();
  8. this.name = name;
  9. }
  10. public String getName() {
  11. return name;
  12. }
  13. public void setName(String name) {
  14. this.name = name;
  15. }
  16. public void hello(){
  17. System.out.println("Hello "+this.getName());
  18. }
  19. }

4、创建Bean配置文件
我在bean的同级目录下创建beans.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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-4.1.xsd">
  3. <bean id="testBean" class="com.gisxx.springTest.TestBean">
  4. <property name="name" value="肖大昕 " />
  5. </bean>
  6. </beans>

5、测试

  1. package com.gisxx.springTest;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class App {
  5. public static void main( String[] args )
  6. {
  7. ApplicationContext context=new ClassPathXmlApplicationContext("com/gisxx/springTest/beans.xml");
  8. TestBean test=(TestBean)context.getBean("testBean");
  9. test.hello();
  10. ((ClassPathXmlApplicationContext)context).close();
  11. }
  12. }

控制台输出:

Hello 肖大昕

原文:http://www.gisxx.com

发表评论

表情:
评论列表 (有 0 条评论,381人围观)

还没有评论,来说两句吧...

相关阅读

    相关 通过 idea、maven 构建spring 项目

    很多小伙伴在开发过程中、都是在原有的项目上做功能添加或修改,很少有直接创建新的项目体验,这篇文章分享一下如何创建spring项目同时把spring 相关jar包换成编译后的sp