02 写一个spring程序

POM

创建一个工程名为 hello-spring 的项目,pom.xml 文件如下:



    4.0.0

    com.funtl
    hello-spring
    1.0.0-SNAPSHOT
    jar

    
        
            org.springframework
            spring-context
            4.3.17.RELEASE
        
    

主要增加了 org.springframework:spring-context 依赖

创建接口与实现

创建 UserService 接口

package com.funtl.hello.spring.service;

public interface UserService {
    public void sayHi();
}

 

创建 UserServiceImpl 实现

package com.funtl.hello.spring.service.impl;

import com.funtl.hello.spring.service.UserService;

public class UserServiceImpl implements UserService {
    public void sayHi() {
        System.out.println("Hello Spring");
    }
}

 

创建 Spring 配置文件

在 src/main/resources 目录下创建 spring-context.xml 配置文件,从现在开始类的实例化工作交给 Spring 容器管理(IoC),配置文件如下:




    

 

  • :用于定义一个实例对象。一个实例对应一个 bean 元素。

  • id:该属性是 Bean 实例的唯一标识,程序通过 id 属性访问 Bean,Bean 与 Bean 间的依赖关系也是通过 id 属性关联的。

  • class:指定该 Bean 所属的类,注意这里只能是类,不能是接口。

  • 配置文件名可以是

    02 写一个spring程序_第1张图片

测试 Spring IoC

创建一个 MyTest 测试类,测试对象是否能够通过 Spring 来创建,代码如下:

package com.funtl.hello.spring;

import com.funtl.hello.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    public static void main(String[] args) {
        // 获取 Spring 容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-context.xml");
        
        // 从 Spring 容器中获取对象
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.sayHi();
    }
}

转自:https://www.funtl.com/zh/spring/%E7%AC%AC%E4%B8%80%E4%B8%AA-Spring-%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F.html#%E6%9C%AC%E8%8A%82%E8%A7%86%E9%A2%91 

我把自己写的源码放在:https://download.csdn.net/download/shmily_syw/11236035

你可能感兴趣的:(java单体应用)