Spring IOC 入门案例

Spring IOC 入门案例

编程工具IDEA,采用maven导入依赖。

主要目录结构

spring_ioc
- src
- - main
- - - java
- - - - com.zhangxin9727.ioc
- - - - - UserService.java
- - - - - UserServiceImp.java
- - - resources
- - - - applicationContext.xml
- - test
- - - java
- - - - SpringIocTest.java
- pom.xml

主要文件内容

pom.xml



<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>
    properties>

    <groupId>com.zhangxin9727groupId>
    <artifactId>spring_iocartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.1.4.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiter-apiartifactId>
            <version>5.4.0version>
            <scope>testscope>
        dependency>
    dependencies>

project>

UserService.java

package com.zhangxin9727.ioc;

public interface UserService {
    void sayHello();
}

UserServiceImp.java

package com.zhangxin9727.ioc;

public class UserServiceImpl implements UserService {
    @Override
    public void sayHello() {
        System.out.println("Hello World!\n你好,世界!");
    }
}

applicationContext.xml



<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="userService" class="com.zhangxin9727.ioc.UserServiceImpl">bean>

beans>

SpringIocTest.java

import com.zhangxin9727.ioc.UserService;
import com.zhangxin9727.ioc.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringIocTest {
    @Test
    //传统方法
    public void test1() {
        UserService userService = new UserServiceImpl();
        userService.sayHello();
    }

    @Test
    //Spring IOC 方法:工厂模式+反射机制+配置文件
    public void test2() {
        //创建Spring工厂
        //获取类路径下的配置文件:ClassPathXmlApplicationContext()
        //获取文件系统下的配置文件:FileSystemXmlApplicationContext()
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        //通过工厂获得UserService类
        UserService userService = (UserService) applicationContext.getBean("userService");
        userService.sayHello();
    }
}

你可能感兴趣的:(SSM,spring)