Spring(1) Spring实现HelloWord

最近有时间来整理一下近一段时间Spring的学习笔记,希望对大家有帮助。
这里我们来用Spring实现一下简单的HelloWord
完整的目录结构如下:
这里写图片描述

1,导入jar包

这里经过测试,只需导入几个必须的jar包,具体可以参考https://spring.io/
这里写图片描述

2,com.java.service包下的Test.java测试类:

package com.java.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.java.test.HelloWorld;

public class Test {
    public static void main(String[] args) {
        //控制反转容器接口
        ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
        HelloWorld helloWorld=(HelloWorld)ac.getBean("helloWorld");
        helloWorld.say();
    }
}

3,com.java.test包下的HelloWord.java:

package com.java.test;

public class HelloWorld {
    public void say(){
        System.out.println("Spring4爸爸你好!");
    }
}

4,配置文件beans.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="helloWorld" class="com.java.test.HelloWorld"></bean>

</beans>

这里的基本配置官方文档也有,大家可以自行查阅

最后测试:
这里写图片描述

代码链接:

猜你喜欢

转载自blog.csdn.net/m0_37293461/article/details/80662232